【ElasticSearch】es索引、映射、文档基本操作&复杂查询
warning:
这篇文章距离上次修改已过192天,其中的内容可能已经有所变动。
from elasticsearch import Elasticsearch
# 连接到Elasticsearch
es = Elasticsearch("http://localhost:9200")
# 创建索引
es.indices.create(index='my_index', ignore=400)
# 获取索引信息
index_info = es.indices.get(index='my_index')
print(index_info)
# 添加/更新文档
doc = {
'name': 'John Doe',
'age': 30,
'about': 'I love to go rock climbing'
}
res = es.index(index='my_index', id=1, document=doc)
print(res['result'])
# 获取文档
doc = es.get(index='my_index', id=1)
print(doc['_source'])
# 更新文档
doc_update = {
'doc': {
'age': 31,
'about': 'I now also love hiking'
}
}
res = es.update(index='my_index', id=1, document=doc_update)
print(res['result'])
# 删除文档
res = es.delete(index='my_index', id=1)
print(res['result'])
# 删除索引
es.indices.delete(index='my_index', ignore=[400, 404])
# 复杂查询示例
query = {
'query': {
'bool': {
'must': [
{'match': {'name': 'John'}}
],
'filter': [
{'term': {'age': 30}}
]
}
}
}
search = es.search(index='my_index', query=query)
print(search['hits']['hits'])
这段代码展示了如何在Python中使用Elasticsearch库来执行基本的索引操作,包括创建索引、获取索引信息、添加/更新文档、获取文档、更新文档和删除文档,以及如何执行一个复杂的查询。
评论已关闭