Search code examples
elasticsearchfacet

Elasticsearch custom Aggregation Result


In my developed training module, there is a page that lists all courses into a table view with filterable header. One of the columns is the "Saved" column which will be "Saved" if I bookmarked it and "Unsaved" if not.

The course entity is indexed as below:

{
  "_index": "myindex",
  "_type": "course",
  "_id": "248fc0a2-06e1-11e6-b740-000c298fdb4d",
  "_score": 1,
  "_source": {
  "boost_number": 1,
  "entity_type_number": 64,
  "course_status_string": "Closed",
  "title": "My Test Course",
  "body": "This is just a test course",
  "created_date": "20160420T101753Z",
  "categories_uuid": [ ],
  "segment_string": [
    "Other"
  ],
  "vertical_string": [
    "Other"
  ],
  "saved_users_uuid": [
    "251bde26-4adf-11e4-b705-000c298fdb4d",
    "00026884-7cc8-11e3-a570-fa163e2bcb7a",
    "00061164-9283-11e5-a394-000c298fdb4d",
    "00110a72-0b8b-11e4-9a64-fa163e2bcb7a",
  ]
}

Let's say I had logged in with id: "251bde26-4adf-11e4-b705-000c298fdb4d". When querying elastic facets, I received this bucket:

"saved_users" : {
    "doc_count_error_upper_bound": 0, 
    "sum_other_doc_count": 0, 
    "buckets" : [ 
        {
            "key" : "251bde26-4adf-11e4-b705-000c298fdb4d",
            "doc_count" : 5
        },
        {
            "key" : "00026884-7cc8-11e3-a570-fa163e2bcb7a",
            "doc_count" : 0
        },
        ...
    ]
}

However, I would like to have another custom bucket such as:

{
  ...
  "buckets": [
    {
      "key": "Saved",
      "doc_count": ...
    },
    {
      "key": "Unsaved",
      "doc_count": ...
    },
  ]
}

Is that possible? How could I do that?


Solution

  • You can try to add the following filters aggregation:

    {
      "size": 0,
      "aggs": {
        "category": {
          "filters": {
            "filters": {
              "Saved": {
                "exists": {
                  "field": "saved_users_uuid"
                }
              },
              "Unsaved": {
                "missing": {
                  "field": "saved_users_uuid"
                }
              }
            }
          }
        }
      }
    }