Query + Aggregations Driven From Query Response

I am hoping the community can point me in the right direction regarding options for performing what I'd describe as a multistep query.

The first "step" of the query is a regular boolean search. Results come back something like this:

      {
        "_index": "properties",
        "_type": "commercial",
        "_id": "71c202e2-9d29-11e9-840b-0e9d35d204a6",
        "_score": 2.7348974,
        "_source": {
          "fips_apn": "06067035-0103-007-0000",
          "property_city": "SACRAMENTO",
          "property_state": "CA"
        }
      },
      {
        "_index": "properties",
        "_type": "commercial",
        "_id": "71c202e5-9d29-11e9-840b-0e9d35d204a6",
        "_score": 2.7348974,
        "_source": {
          "fips_apn": "06067035-0111-014-0000",
          "property_city": "SACRAMENTO",
          "property_state": "CA"
        }
      }

I'm hoping to add to each response the aggregate number of indexed records that share the same fips_apn value.

For example, in the following response, 4 records would have fips_apn=06067035-0111-014-0000 and 6 records would have fips_apn=06067035-0103-007-0000:

      {
        "_index": "properties",
        "_type": "commercial",
        "_id": "71c202e2-9d29-11e9-840b-0e9d35d204a6",
        "_score": 2.7348974,
        "_source": {
          "fips_apn": "06067035-0103-007-0000",
          "fips_apn_count": 6,      <----------------*
          "property_city": "SACRAMENTO",
          "property_state": "CA"
        }
      },
      {
        "_index": "properties",
        "_type": "commercial",
        "_id": "71c202e5-9d29-11e9-840b-0e9d35d204a6",
        "_score": 2.7348974,
        "_source": {
          "fips_apn": "06067035-0111-014-0000",
          "fips_apn_count": 4,       <----------------*
          "property_city": "SACRAMENTO",
          "property_state": "CA"
        }
      }

Is there a straightforward way of accomplishing this type of aggregation based on a value that comes back as part of a result? Or will this require a separate aggregation-focused query?

Thanks in advance for your help! I appreciate it :slight_smile:

Indeed there is: Use a terms aggregation on the fips_apn field.

The response structure is different than what you are describing, but the idea is to group documents by a certain field value and then return a count of the documents in each of those buckets (you can go more fancy but this is the start of it).

Hello,

How do you want to use this? I can share a sample of this using the Java REST API, but no use if that is not your use case.

Jurgen