[ Python使用ElasticSearch官方包 ]


目录:

1. 安装

  • pip install elasticsearch
  • pip install elasticsearch==7.13.1
  • 官方

2. 基本使用

参考文档 - 百度文档1 - 百度文档2 - 百度文档3

# from django.shortcuts import render
from elasticsearch import Elasticsearch
es = Elasticsearch(hosts=["http://localhost:9200"],
                   sniff_on_start=True, sniff_on_connection_fail=True)


# 判断索引是否存在
if not es.indices.exists(index='test_index'):
    mymapping = {
        "mappings": {
            "properties": {
                "title": {
                    "type": "text",
                    "analyzer": "ik_max_word"
                },
                "content": {
                    "type": "text",
                    "analyzer": "ik_max_word"
                },
                "date": {
                    "type": "date",
                    "format": "yyyy/MM/dd"
                },
                "id": {
                    "type": "integer"
                }
            }
        }
    }
    # 创建索引
    es.indices.create(index='test_index', body=mymapping)

body = {
    "title": "你好阿",
    "content": "谢谢你",
    "date": "2022/12/11",
    "id": 2
}

# 索引里添加文档
res = es.index(index='test_index', id=2, body=body)

print(res)
# 查询索引里的文档
res = es.get(index='test_index', id=2)
print(res)