基于AND运算符的多词Multi Match Query多字段查询实现咨询
Got it, let's build the Elasticsearch query you need for that Udemy-like top bar search with multi-keyword support. Your requirement calls for a Multi Match Query with AND operator across your specified fields, including the nested designers field. Here's a complete, tailored solution:
Final Query DSL
POST /your_index/_search { "query": { "bool": { "should": [ // Match flat fields: category (keyword) and story (text) { "multi_match": { "query": "your_user_search_input", "fields": ["category", "story"], "operator": "AND", "type": "cross_fields", "tie_breaker": 0.3 } }, // Match nested designers.name (keyword) { "nested": { "path": "designers", "query": { "multi_match": { "query": "your_user_search_input", "fields": ["designers.name"], "operator": "AND" } }, "inner_hits": {} // Optional: return matched nested designer objects } } ], "minimum_should_match": 1 // Ensure at least one field group matches all keywords } } }
Key Breakdown & Why This Works
Let's walk through the important parts to make sure it aligns with your mappings and use case:
Bool Should + Minimum Should Match
We useshouldto let the query match either the flat field group or the nested designer field group, then setminimum_should_match: 1to ensure at least one of these groups satisfies the AND keyword condition. This way, users' multi-keyword input can match across any of your target fields while enforcing all keywords are present in the matched group.Multi Match for Flat Fields
operator: "AND": Ensures every keyword in the user's input is found in eithercategoryorstory(thanks to thecross_fieldstype, which treats multiple fields as a single combined pool for matching).type: "cross_fields": Perfect for this scenario—it lets keywords split across different fields count as a match (e.g., "java" incategoryand "beginner" instorystill qualifies, whereasbest_fieldswould require both terms in the same field).tie_breaker: Balances scoring between exact keyword matches (likecategory) and full-text matches (likestory) so results feel intuitive.
Nested Query for Designers
Sincedesignersis a nested type, we can't query it directly with a top-level multi-match. Thenestedclause targets thedesigners.namekeyword field, applying the same AND operator to ensure all user keywords match a designer's name. The optionalinner_hitsreturns which specific designer matched, which is great for displaying context in search results.
Quick Adjustments for Your Needs
- If you want to require matches in both flat fields and nested designers, swap
shouldformustin the bool clause. - For case-insensitive matching on keyword fields (e.g., "web dev" matching "Web Dev"), add a lowercase normalizer to your
categoryanddesigners.namemappings.
This setup gives you the exact Udemy-style search experience where users can type multiple keywords and get results that include all terms across your target fields.
内容的提问来源于stack exchange,提问作者fullmetal

