James Burke
James Burke

Reputation: 2387

how to aggregate results and create arrays on certain fields

I'm new to elasticsearch and not sure where to begin with this.

Here is my data in ES:

[{
  product_id: "xxxyyyxx",
  shop_id: "shop1",
  name: "Elastic testing",
  creator: "Test 1337",
  price: 13
},
{
  product_id: "xxxyyyxx",
  shop_id: "shop2",
  name: "Elastic testing",
  creator: "Test 1337",
  price: 10
}]

What I want to get

{
  product_id: "xxxyyyxx",
  shops: ['shop1', 'shop2'],
  name: "Elastic testing",
  creator: "Test 1337",
  min_price: 10,
  max_price: 13
}

Here is what I have so far, which only returns the results without aggregation...

query: {
  multi_match: {
    query: 'test',
    fields: ['creator', 'name', 'info']
  }
}

if you can point me in the right direction of where to start, much appreciated.

Upvotes: 0

Views: 131

Answers (2)

aHochstein
aHochstein

Reputation: 515

Have a look into aggregations. There a aggregations that group your data into so called buckets, and aggregations that you can use on that buckets to calculate metrics. An example for metric would be your need for min and max price. You can nest aggregations, to get your desired result.

Aggregations are defined outside of the query, the matches for your query are used as input data.

In your usecase, you could use a terms aggregation on the name field, this will provide you with a bucket for every name. If you then use a metric for max and min on this bucket you already have a part of the desired result.

Regarding the shopIds,you will need to nest another bucket aggregation which will provide you with a bucket for every single value of the fiels shopId containing all documents with that value.

Example:

"query": { //your query here ...},
    "aggs" : {
        "name_term" : {
            "terms" : { "field" : "name" },
            "aggs" : {
                "max_price" : { "max" : { "field" : "price" } },
                "min_price" : { "min" : { "field" : "price" } },
                "shops" : {
                    "terms" : { "field" : "shop_id" }
                }
            } 
        }
    }

Upvotes: 2

Maica Ballangan
Maica Ballangan

Reputation: 18

creating an array of ids is declared the same as declaring a normal field:

"product_id": {
    "type": "keyword",
    "store": "true",
    "index": "true"
}

Just make sure that your array is named as product_id in your class:

List<String> product_id

Upvotes: 0

Related Questions