1. 连接到 Elasticsearch 集群
from elasticsearch import Elasticsearch
# 连接到 Elasticsearch 集群
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
# 检查连接是否成功
if es.ping():
print('Connected to Elasticsearch')
else:
print('Could not connect to Elasticsearch')
2. 简单的全文搜索
# 定义搜索请求体
search_body = {
"query": {
"match": {
"title": "Elasticsearch Tutorial"
}
}
}
# 执行搜索
index_name = "your_index_name"
response = es.search(index=index_name, body=search_body)
# 处理搜索结果
for hit in response['hits']['hits']:
print(f"Document ID: {hit['_id']}, Score: {hit['_score'