Elasticsearch 5.5单查询排序:优先返回name=Ram数据再按activity排序
Alright, let's figure out how to build this Elasticsearch 5.5 query to meet your needs. You want all documents where name is 'Ram' to show up first, then the rest sorted by the activity field. Here are two solid approaches to make that happen:
Approach 1: Script-Based Priority Sorting
This method uses a custom script in the sort clause to explicitly prioritize documents where name equals 'Ram', then sorts the remaining results by activity. It's straightforward and easy to read.
{ "query": { "match_all": {} }, "sort": [ { "_script": { "type": "number", "script": { "inline": "doc['name'].value == 'Ram' ? 1 : 0" }, "order": "desc" } }, { "activity": { "order": "asc" } } ] }
Breakdown:
- The
match_allquery fetches all your documents. - The first sort condition runs a small script that assigns a value of
1to documents wherenameis 'Ram', and0to everything else. Sorting indescorder pushes all the 'Ram' entries to the top. - The second sort condition takes care of ordering the non-Ram documents by the
activityfield (usedescinstead ofascif you want reverse alphabetical order).
Note: If your name field is mapped as a text type (instead of keyword), you'll need to reference the keyword sub-field in the script like this: doc['name.keyword'].value to ensure exact matching. Also, make sure your Elasticsearch cluster allows inline scripts (adjust script.inline: true in elasticsearch.yml if needed for testing).
Approach 2: Function Score Boosting
If you prefer working with query scores instead of custom scripts, you can use function_score to give a massive boost to documents matching 'Ram', then sort by score first and activity second.
{ "query": { "function_score": { "query": { "match_all": {} }, "functions": [ { "filter": { "term": { "name": "Ram" } }, "boost_factor": 1000 } ], "boost_mode": "multiply" } }, "sort": [ { "_score": "desc" }, { "activity": "asc" } ] }
Breakdown:
- The
function_scorewraps our basematch_allquery and applies a boost factor of 1000 to any document that matches thetermfilter forname: Ram. This makes their relevance score way higher than other documents. - We then sort first by
_scorein descending order (so boosted 'Ram' docs come first), followed by theactivityfield.
Either approach will get you the results you need. The script-based method is more explicit about your priority logic, while the function score method leverages Elasticsearch's built-in scoring system.
内容的提问来源于stack exchange,提问作者Shajesh

