es9:python:搜索文档/列出索引中所有文档

一,代码:

 

from elasticsearch import Elasticsearch

# 连接到 Elasticsearch,替换为实际的 IP 地址和密码
# , basic_auth=('elastic', 'Elastic_j625sz')
es = Elasticsearch('http://127.0.0.1:9200')

# 检查连接
if es.ping():
    print('连接成功')
else:
    print('连接失败')

index_name = "my_index2"

# 检查索引是否存在
is_exist = es.indices.exists(index=index_name)
print("索引"+index_name+"是否存在:"+str(is_exist))
if is_exist == False:
    # 创建索引
    es.indices.create(index=index_name)

# 添加文档
doc1 = {
    "title": "测试文档1",
    "content": "这是一个测试文档1",
    "timestamp": "2024-12-07"
}
doc2 = {
    "title": "测试文档2",
    "content": "这是一个测试文档2",
    "timestamp": "2024-12-01"
}
# 指定ID1插入
es.index(index=index_name, id="1", document=doc1)
# 指定ID2插入
es.index(index=index_name, id="2",document=doc2)


# 列出所有文档:
body = {
    "query":{
        "match_all":{}
    },
    'size':100,
}

res = es.search(index=index_name,body=body)
print("列出所有文档:")
print(res)


# 搜索文档
query = {
    "query": {
        "match": {
            "title": "文档"
        }
    },
    'size':100,
}

search_result = es.search(index=index_name, body=query)
print("搜索结果:")
print( search_result )

 

二,测试结果:

$ python3 seek.py 
连接成功
索引my_index2是否存在:True
列出所有文档:
{'took': 1, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 2, 'relation': 'eq'}, 'max_score': 1.0, 
                                                                                                              'hits': [{'_index': 'my_index2', '_id': '1', '_score': 1.0, '_source': {'title': '测试文档1', 'content': '这是一个测试文档1', 'timestamp': '2024-12-07'}}, 
                                                                                                                       {'_index': 'my_index2', '_id': '2', '_score': 1.0, '_source': {'title': '测试文档2', 'content': '这是一个测试文档2', 'timestamp': '2024-12-01'}}]}}
搜索结果:
{'took': 3, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 2, 'relation': 'eq'}, 'max_score': 0.26706278, 
                                                                                                              'hits': [{'_index': 'my_index2', '_id': '1', '_score': 0.26706278, '_source': {'title': '测试文档1', 'content': '这是一个测试文档1', 'timestamp': '2024-12-07'}}, 
                                                                                                                       {'_index': 'my_index2', '_id': '2', '_score': 0.26706278, '_source': {'title': '测试文档2', 'content': '这是一个测试文档2', 'timestamp': '2024-12-01'}}]}}

 

posted @ 2025-12-17 19:20  刘宏缔的架构森林  阅读(1)  评论(0)    收藏  举报