ElasticSearch 6.x:简化语法实现标题与描述字段短语匹配检索
Got it, let's build the Elasticsearch 6.x query you need to handle searches across the title and description fields, using the bool, should, must, and match_phrase components as requested. This structure will effectively handle queries like "change desk chair" while keeping the syntax clean and simplified.
Here's the working query:
{ "query": { "bool": { "must": [ { "multi_match": { "query": "change desk chair", "fields": ["title", "description"], "operator": "and" } } ], "should": [ { "match_phrase": { "title": "change desk chair" } }, { "match_phrase": { "description": "change desk chair" } } ], "minimum_should_match": 0 } } }
Breakdown of the Query:
mustClause: This ensures every term from the user's query ("change", "desk", "chair") exists in either thetitleordescriptionfield. We usemulti_matchhere to avoid repeating logic for each field, withoperator: "and"enforcing all terms are present.shouldClause: This adds exact phrase matching for the full query string in each field. Documents that have the exact phrase intitleordescriptionwill get a higher relevance score, so more precise matches rise to the top.minimum_should_match: 0: This keeps the query flexible—documents don't need to have the exact phrase to be returned, but phrase matches still get a boost.
For your example document (title: "Change my room!", description: "I change my desk and chair. These make my room more beautiful!"), this query will correctly match it because all three query terms are present in the description field. If any document had the exact phrase "change desk chair" in either field, it would rank higher than partial matches.
内容的提问来源于stack exchange,提问作者JSKIM

