How to search exact phrase in string field with ElasticSearch?

匆匆过客 提交于 2019-12-23 12:27:05

问题


I want to search "Marketing in social networks" inside documents. All together. But i continue getting results with words separated. i have the following DSL query:

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

I do not have documents that contain this phrase and title but i also get results(documents) with the words of the phrase to search splitted. I want a strict search. If there is not any document that have this phrase do not retrieve any document or only retrieve documents with that title. Why operator and does not work?


回答1:


Can you try like below using type phrase. See here it says,

query first analyzes the query string to produce a list of terms. It then searches for all the terms, but keeps only documents that contain all of the search terms, in the same positions relative to each other

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

P.S: I haven't tried it yet.




回答2:


First answer is good but for ES v5 using "type":"phrase" will return [WARN ][org.elasticsearch.deprecation.common.ParseField] Deprecated field [type] used, replaced by [match_phrase and match_phrase_prefix query] in the headers
So correct query should contain match_phrase:

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


来源:https://stackoverflow.com/questions/39931006/how-to-search-exact-phrase-in-string-field-with-elasticsearch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!