osynavets
osynavets

Reputation: 1520

Specify size for each subquery in Elasticsearch

I have query that is similar to union operation in SQL. What i need is to specify the size of result set for each index. For example i want to get 10 records from first index and 15 records from second index.

My query:

{
    "query": {
        "bool": {
            "should": [
                {
                    "bool": {
                        "must": [{
                            "match_phrase_prefix": {"userName": "ar" }
                        }]
                    }
                },
                {
                    "bool": {
                        "must": [{
                            "match_phrase_prefix": { "groupName": "ar" }
                        }]
                    }
                }
            ]
        }
    }
}

Url to send query: http://website.com:9200/user_data,group_data/_search

If you have any thoughts i'd be very grateful. Thank you

Upvotes: 0

Views: 619

Answers (2)

osynavets
osynavets

Reputation: 1520

Ok, thanks for help

Eventually i've chosen another approach. I use Multi Search API, which allows you executing several requests at once. My query is:

POST http://website.com:9200/_msearch

{"index": "user_data"}
{"size":10,"query":{"bool":{"must":[{"match_phrase_prefix":{"userName":"##USER_TEXT##"}}]}}}
{"index": "group_data"}
{"size":15,"query":{"bool":{"must":[{"match_phrase_prefix":{"groupName":"##USER_TEXT##"}}]}}}

Upvotes: 0

Kevin Quinzel
Kevin Quinzel

Reputation: 1428

I think you can't do that with a simple query.

But can do that with the Top Hits aggregation, which lets you group result sets by certain fields via a bucket aggregator. Your case should look like:

{
     "query": {
        "bool": {
            "should": [
                {
                    "bool": {
                        "must": [{
                            "match_phrase_prefix": {"userName": "ar" }
                        }]
                    }
                },
                {
                    "bool": {
                        "must": [{
                            "match_phrase_prefix": { "groupName": "ar" }
                        }]
                    }
                }
            ]
        }
     }, #Your query stills the same
     "size": 0, #This will bring back nothing within the field "hits", so you can focus in the "aggregations" field.
     "aggs": {
         "10_usernames": {
             "top_hits": {
                 "_source": {
                     "includes": [ "userName" ]
                 },
                 "size" : 10
             }
         },
         "15_groupames": {
             "top_hits": {
                 "_source": {
                     "includes": [ "groupName" ]
                 },
                 "size" : 15
             }
         }

     }
}

You'll see your results within the "aggregations" field.

Hope this is helpful! :D

Upvotes: 2

Related Questions