Conditional aggregation based on index name

Viewed 70

I need to add functionality to an existing project. Until now our fulltext serach only sent index list and query string to elasticsearch(from our js backend):

return this.client.search({
    index,
    size: pageSize,
    from: currentPage <= 1 ? 0 : (currentPage - 1) * pageSize,
    body: {
        query: {
            query_string: queryObject
        }
    }
});

Until now and still currently we either search by on of the specific indexes, index = 'quotes' or index = 'opportunities', or we serach by all of them at once, index = ['quotes', 'opportunities', ...] Now, I was asked to add to this search the following:

  1. If the search is done only in index quotes, then add logic to only search for quotes which have highest version field value inside a group of all quotes with same master_id field value
  2. If we search in multiple indexes, then only apply this grouping by master_id and filtering by max version to the quotes index

What I have so far is I've added aggregation which contains results of quotes, grouped by master_id and only the one with highest version is added to the result inside aggregation:

return this.client.search({
    index,
    size: pageSize,
    from: currentPage <= 1 ? 0 : (currentPage - 1) * pageSize,
    body: {
        aggs: {
            groupByMasterId: {
                terms: {
                    field: 'master_id'
                }
            },
            aggs: {
                top_hits: {
                    size: 1,
                    sort: [
                        {
                            version: 'desc'
                        }
                    ]
                }
            }
        },
        query: {
            query_string: queryObject
        }
    }
});

I need help with this:

  1. is there a way to return the result of aggregation inside hits object instead of aggregations object ? Or do I also have to add separate logic to extract these quotes results from aggregations object of Elasticsearch response ?
  2. If the multiple indexes are being searched in single query, can I apply this aggregation only to a specific index ? Or are aggregations done on all results from all the indexes ?

Thanks

0 Answers
Related