我有数百万个文档要索引。每个文档都有字段doc_id和doc_title几个字段doc_content。
import requests
index = 'test'
JSON = {
"mappings": {
"properties": {
"doc_id": {"type": "keyword"},
"doc_title": {"type": "text" },
"doc_content": {"type": "text" }
}
}
}
r = requests.put(f'http://127.0.0.1:9200/{index}', json=JSON)
为了最小化索引的大小,我保留doc_title并doc_content分开。
docs = [
{"doc_id": 1, "doc_title": "good"},
{"doc_id": 1, "doc_content": "a"},
{"doc_id": 1, "doc_content": "b"},
{"doc_id": 2, "doc_title": "good"},
{"doc_id": 2, "doc_content": "c"},
{"doc_id": 2, "doc_content": "d"},
{"doc_id": 3, "doc_title": "bad"},
{"doc_id": 3, "doc_content": "a"},
{"doc_id": 3, "doc_content": "e"}
]
for doc in docs:
r = requests.post(f'http://127.0.0.1:9200/{index}/_doc', json=doc)
查询_1:
JSON = {
"query": {
"match": {
"doc_title": "good"
}
}
}
r = requests.get(f'http://127.0.0.1:9200/{index}/_search', json=JSON)
[x['_source'] for x in r.json()['hits']['hits']]
[{'doc_id': 1, 'doc_title': 'good'}, {'doc_id': 2, 'doc_title': 'good'}]
查询_2:
JSON = {
"query": {
"match": {
"doc_content": "a"
}
}
}
r = requests.get(f'http://127.0.0.1:9200/{index}/_search', json=JSON)
[x['_source'] for x in r.json()['hits']['hits']]
[{'doc_id': 1, 'doc_content': 'a'}, {'doc_id': 3, 'doc_content': 'a'}]
如何结合 query_1 和 query_2?
我需要这样的东西:
JSON = {
"query": {
"bool": {
"must": [
{"match": {"doc_title": "good"}},
{"match": {"doc_content": "a"}}
]
}
}
}
r = requests.get(f'http://127.0.0.1:9200/{index}/_search', json=JSON)
[x['_source'] for x in r.json()['hits']['hits']]
[]
期望的结果:
[{'doc_id': 1, 'doc_title': 'good', 'doc_content': 'a'}]
函数式编程
相关分类