我有一个包含三个字符串字段“user_id”、“headline”和“note”的索引。我想搜索 A)属于特定用户并且 B)在“标题”或“注释”中具有文本匹配的文档。我正在使用 AWS Elasticsearch 7.4,并且没有完成任何架构或映射 - 我只是开始根据索引发布文档。
我尝试的是这样的:
query = {
"bool": {
"should": [
{"match": {"headline": search_text}},
{"match": {"note": search_text}}
],
"must": {"match": {"user_id": user_id}}
}
}
这有效,但它会找到搜索文本与“标题”或“注释”不匹配的文档。基本上我需要一个 bool 查询: user_id = :user_id AND (headline = :search_text OR note = :search_text)
最佳答案
由于 bool 子句的不正确使用,您现有的查询无法正常工作,其工作根据请参阅 https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html有关 bool 查询的更多详细信息
user_id = :user_id OR (headline = :search_text OR note = :search_text)
在我的本地使用示例文档测试了完整的工作示例:
通过定义映射对三个示例文档建立索引:
{
"user_id" : "1",
"headline" : "today",
"note" : "today"
}
{
"user_id" : "1",
"headline" : "tomorrow",
"note" : "today"
}
{
"user_id" : "1",
"headline" : "tomorrow",
"note" : "tomorrow"
}
根据您的情况,搜索user_id
1
和 text
= today
时仅搜索 doc 1 和 2必须归还。
正确的搜索查询
{
"query": {
"bool": {
"must": [
{
"match": {
"user_id": "1"
}
},
{
"multi_match": {
"query": "today",
"fields": [
"headline",
"note"
]
}
}
]
}
}
}
搜索结果
"hits": [
{
"_index": "booleanaws",
"_type": "_doc",
"_id": "1",
"_score": 1.1143606,
"_source": {
"user_id": "1",
"headline": "today",
"note": "today"
}
},
{
"_index": "booleanaws",
"_type": "_doc",
"_id": "2",
"_score": 0.603535,
"_source": {
"user_id": "1",
"headline": "tomorrow",
"note": "today"
}
}
]
关于elasticsearch - 如何在 Elasticsearch 中编写执行 field1 AND (field2 OR field3) 的 bool 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62734165/