Elasticsearch - sort a query with multiple indexes

I create an autocomplete search using elasticsearch, so I need to query 3 indexes for posts , comments , authors . I have the following query:

 { "query":{ "query_string":{ "query":"something" } } } 

call:

 curl -X GET 'http://localhost:9200/posts,comments,authors/_search?pretty' -d '{ "query": { "query_string": { "query": "something" } } }' 

I need to sort the results by specific index fields, for example:

index has a field called comments_count , votes_count comments_count , and posts_count authors. When comparing posts, it should be sorted by comments_count , when comments then votes_count , when authors then posts_count .

Is there anything you can do? I would not want to combine indexes into one, because they index completely different documents.

+4
source share
3 answers

Well, my problem was that if I sort by field not found in all indexes, the documents will not be returned.

I managed to solve:

 { "_script":{ "script":"type=doc['_type'].value;if(type=='posts'){return doc['comments_count'].value} else {return 0};", "type":"number", "order":"desc" } } 

at least now documents are displayed, even if below.

+2
source

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html

Use ignore unmapped_type to ignore the field when querying multiple indexes, and the field does not exist in other indexes.

0
source

Instead of using comments_count , votes_count and posts_count you can put the same name in the index (for example, items_count ) and do the usual sorting:

 { "sort": [ { "items_count": "desc" } ] } 

If there are other objects that do not have items_count , there is an option to ignore unmarked fields :

 { "sort": [ { "items_count": { "order": "desc", "unmapped_type": "long" } } ] } 
0
source

Source: https://habr.com/ru/post/1483913/


All Articles