Amir Afianian
Amir Afianian

Reputation: 2795

elasticsearch get unique values, and the values count on multiple fields

I want to get the list of unique values from a field, and at the same time, count how many times each of those unique values have appeared in two different fields.

Let's say I have a product that can be both bought and sold. I want to query: Unique values that have appeared in the field sold, AND, count how many times each value has appeared in both sold, and bought fields.

The closest I came so far is terms aggregation I get to have both values, but in two different buckets:

{
  "aggs": {
    "sold": {
      "terms":{
        "field": "productname.sold.keyword",
        "size": 1000
      }
    },
    "bought": {
      "terms":{
        "field": "product.bought.keyword",
        "size": 1000
      }
    }
  }
}

But it gives me the result in two seperate buckets. My ideal output is like this:

  "aggregations": {
    "product_stat": {
      "key": "<product>"
      "sold": "<#>"
      "bought": "<#>"
    }
  }

How should I form my query to achieve so? I want to get unique values of sold, and count how many times that value has appeared in sold and bought fields.

Upvotes: 0

Views: 1368

Answers (1)

Lupanoide
Lupanoide

Reputation: 3222

Try:

  body = {
  "size": 0,
  "aggs": {
    "sold": {
      "terms": {
        "field": "product.sold.keyword",
        "size": 40000
      },
      "aggs": {
        "bought": {
          "terms": {
            "field": "product.bought.keyword",
            "size": 40000
          }
        }
      }
    }
  }
}

Upvotes: 1

Related Questions