如何使用ElasticSearch在字符串字段中搜索确切的短语?

时间:2016-10-08 09:52:38

标签: elasticsearch full-text-search

我想在社交网络中搜索"营销"内部文件。全部一起。但我继续得到结果与单词分开。我有以下DSL查询:

{
    "fields": ["title"], 
    "query": {
        "bool": {
            "should": [{
                "match": {
                    "title": "SEO"
                }
            }],
            "must": [{
                "match": {
                    "content": {
                        "query": "Marketing in social networks",
                        "operator": "and"
                    }
                }
            }]
        }
    }
}

我没有包含此短语和标题的文档,但我也得到了结果(文档),其中包含要搜索splitted的短语。我想要严格的搜索。如果没有任何具有此短语的文档,则不检索任何文档或仅检索具有该标题的文档。 为什么运算符和不起作用?

2 个答案:

答案 0 :(得分:7)

你可以尝试使用类型短语。见here它说,

  

查询首先分析查询字符串以生成术语列表。它   然后搜索所有条款,但只保留包含的文档   所有搜索词,相对于彼此的相同位置

{
    "fields": ["title"], 
    "query": {
        "bool": {
            "should": [{
                "match": {
                    "title": "SEO"
                }
            }],
            "must": [{
                "match": {
                    "content": {
                        "query": "Marketing in social networks",
                        "type":  "phrase"
                    }
                }
            }]
        }
    }
}
P.S:我还没有尝试过。

答案 1 :(得分:5)

第一个答案很好但是对于使用"type":"phrase"的ES v5,会在标题中返回[WARN ][org.elasticsearch.deprecation.common.ParseField] Deprecated field [type] used, replaced by [match_phrase and match_phrase_prefix query] 因此,正确的查询应包含match_phrase

 {
    "fields": ["title"], 
    "query": {
        "bool": {
            "should": [{
                "match": {
                    "title": "SEO"
                }
            }],
            "must": [{
                "match_phrase": {
                    "content": {
                        "query": "Marketing in social networks"
                    }
                }
            }]
        }
    }
}