Elasticsearch search term aggregation

Viewed 22

I have the following mappings:

{
  mappings: {
    properties: {
      id: { type: "keyword" },
      tags: {
        properties: {
          text: { type: "text" },
          keyword: { type: "keyword" },
        },
      },
    },
  },
}

Here is some example data:

[
  {
    id: '05070ff6-a7f1-4fad-ad70-e91fd87d58fb',
    tags: ['these','are','some','tags']
  },
  {
    id: '4843beba-4621-474f-bd80-281300fd0091',
    tags: ['abc']
  }
]

My query looks like this:

{
  "size": 0,
  "query": {
    "bool": {
      "must": {
        "bool": {
          "should": [
            {
              "match": {
                "tags.text": "are"
              }
            },
            {
              "prefix": {
                "tags.text": "are"
              }
            },
            {
              "wildcard": {
                "tags.text": {
                  "value": "*are*",
                  "case_insensitive": true
                }
              }
            },
            {
              "wildcard": {
                "tags.text": {
                  "value": "*are",
                  "case_insensitive": true
                }
              }
            },
            {
              "wildcard": {
                "tags.text": {
                  "value": "are*",
                  "case_insensitive": true
                }
              }
            }
          ]
        }
      }
    }
  },
  "aggs": {
    "uniq_tags": {
      "terms": {
        "field": "tags.keyword",
        "size": 500
      }
    }
  }
}

I would expect the response to return ['are'] but it instead returns ['these', 'are, 'some, 'tags'].

I know I need to aggregate before filtering but my issue is that I need to filter on tags.text but Elasticsearch wants me to aggregate on tags.keyword. I'm not sure how to format the query to accomplish this.

1 Answers
  1. If you want to get only matching tags back you should use nested field with nested query

  2. Aggregations only work on keyword fields (there is a way to apply them to text fields with fielddata parameter but this is not recommended) so you'll have to run query on tags.text but aggregations on tags (or whatever it will be with nested)

Related