Return unique results in elasticsearch Return unique results in elasticsearch elasticsearch elasticsearch

Return unique results in elasticsearch


There is no direct way of doing this. But you can follow these steps to get desired result.

Step 1. You should know all parentid. This data can be obtained by doing a simple terms aggregation (Read more here) on field parentid and you will get only the list of parentid, not the documents matching to that. In the end you will have a smaller array on than you are currently expectig.

{  "aggs": {    "parentids": {      "terms": {        "field": "parentid",        "size": 0       }    }  }}

size: 0 is required to return all results. Read more here.

OR

If you already know list of all parentid then you can directly move to step 2.

Step 2. Fetch related documents by filtering documents by parentid and here you can apply pagination.

{  "from": 0,  "size": 20,   "query": {    "filtered": {      "query": {        "match_all": {}      },      "filter": {        "term": {          "parentid": "2222"        }      }    }  }}

from and size are used for pagination, so you can loop through each of parentid in the list and fetch all related documents.


If you are just looking for all names grouped by parent id, you can use below query:

 {      "query": {        "match_all": {}      },"aggs": {        "parent": {          "terms": {            "field": "parentid",            "size": 0          },"aggs": {            "NAME": {              "terms": {                "field": "name",                "size": 0              }            }          }        }      },"size": 0    }

If you want the entire document grouped by parentdId, it will be a 2 step process as explained by Sumit above and you can use pagination there.

Aggregation doesn't give you access to all documents/document-ids in the agg result, so this will have to be a 2 step process.