[英]How to get all documents under an elasticsearch index with python client ?
我正在嘗試使用 python 客戶端獲取所有索引文檔,但結果只顯示第一個文檔這是我的 python 代碼:
res = es.search(index="92c603b3-8173-4d7a-9aca-f8c115ff5a18", doc_type="doc", body = {
'size' : 10000,
'query': {
'match_all' : {}
}
})
print("%d documents found" % res['hits']['total'])
data = [doc for doc in res['hits']['hits']]
for doc in data:
print(doc)
return "%s %s %s" % (doc['_id'], doc['_source']['0'], doc['_source']['5'])
Elasticsearch 默認只檢索 10 個文檔。 您可以在此處更改此行為 - doc 。 分頁的最佳實踐是search after query
和scroll query
。 這取決於您的需求。 請閱讀此答案彈性搜索不提供大數字的頁面大小數據
要顯示所有結果:
for doc in res['hits']['hits']:
print doc['_id'], doc['_source']
嘗試“_doc”而不是“doc”
res = es.search(index="92c603b3-8173-4d7a-9aca-f8c115ff5a18", doc_type="_doc", body = {
'size' : 100,
'query': {
'match_all' : {}
}
})
您可以嘗試以下查詢。 它將返回所有文件。
result = es.search(index="index_name", body={"query":{"match_all":{}}})
您還可以使用elasticsearch_dsl
及其搜索 API,它允許您通過scan
方法迭代所有文檔。
import elasticsearch
from elasticsearch_dsl import Search
client = elasticsearch.Elasticsearch()
search = Search(using=client, index="92c603b3-8173-4d7a-9aca-f8c115ff5a18")
for hit in search.scan():
print(hit)
我沒有看到提到如果您剛剛添加數據就必須刷新索引。 用這個:
es.indices.refresh(index="index_name")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.