Glorfindel
Glorfindel

Reputation: 22641

How can I use a Term Query to search within this array?

I have an index where certain properties of my document can be array-valued IDs, i.e.

POST temp/_doc
{
  "test": ["5T8QLHIBB_kDC9Ugho68","5T8QLHIBB_kDC9Ugho69"]
}

Now, when I want to search documents containing a certain ID, a term query like this one:

POST temp/_search
{
  "query": {
    "term": {
      "test": "5T8QLHIBB_kDC9Ugho68"
    }
  }
}

gives no results. If I try it with simpler values (e.g. "foo" and "bar" instead of the IDs), it works. How can I solve this?

Upvotes: 0

Views: 2912

Answers (2)

Joe - Check out my books
Joe - Check out my books

Reputation: 16925

I'd add to your answer that there's no 'complexity' distinction between the string hey and 5T8QLHIBB_kDC9Ugho68 -- they get analyzed equally.

As to the array aspect which may be confusing at first -- there is no dedicated array data type in ES. You should define the mapping for the array values as strings (or keywords).

Side note: it's recommended not to intermix different types in one particular array -- but you're good to go w/ ["5T8QLHIBB_kDC9Ugho68", "5T8QLHIBB_kDC9Ugho69"]

Upvotes: 0

Glorfindel
Glorfindel

Reputation: 22641

In this case, instructing Elasticsearch to use the keyword part of the field works:

POST temp/_search
{
  "query": {
    "term": {
      "test.keyword": "5T8QLHIBB_kDC9Ugho68"
    }
  }
}

gives one hit.

I could have avoided this situation by specifying the mapping upfront like this, instead of letting Elasticsearch guess it based on the document I posted; by default, it will use a text field instead of a keyword.

POST temp/_mapping
{
  "properties": {
    "test": {
      "type": "keyword"
    }
  }
}

Upvotes: 3

Related Questions