Manuel Spigolon
Manuel Spigolon

Reputation: 12870

How to index some fields of an object

I have to log a dynamic object, but I'm interested only to index some fields (not all), but when I configure this behaviour I can't search for those fields.

Here an example of what I'm doing with Elastic 6.x:

curl --request PUT 'http://localhost:9200/manuel-prova?pretty' \
--header 'Content-Type: application/json' \
--data-raw '{
  "mappings": {
    "log": {
      "properties": {
        "hello": {
          "type": "object",
          "enabled": false,
          "properties": {
            "my-api-key": {
              "type": "text"
            }
          }
        },
        "check": {
          "type": "boolean"
        }
      }
    }
  }
}'

Then I insert the data:

curl --request POST 'http://localhost:9200/manuel-prova/log?pretty' \
--header 'Content-Type: application/json' \
--data-raw '{
  "hello": {
    "foo": "bar",
    "my-api-key": "QWERTY"
  },
  "check": true
}'

Finally, I tried to query:

curl --request POST 'http://localhost:9200/manuel-prova/_search?pretty' \
--header 'Content-Type: application/json' \
--data-raw '{
  "query": {
    "bool": {
      "must": [
        { "exists": { "field": "hello.my-api-key" } }
      ]
    }
  }
}'

This query doesn't work.

If I change to { "exists": { "field": "check" } } for example, it works.

Do you have any suggestion?

Upvotes: 0

Views: 74

Answers (1)

Val
Val

Reputation: 217304

This is because your hello object is defined with enabled: false, which makes ES ignore the content of the field altogether, and hence, it is not searchable.

In order to fix that you need to remove enabled: false, like below, and it will work:

curl --request PUT 'http://localhost:9200/manuel-prova?pretty' \
--header 'Content-Type: application/json' \
--data-raw '{
  "mappings": {
    "log": {
      "dynamic": false,          <-- add this
      "properties": {
        "hello": {
          "type": "object",
          "properties": {        <-- remove enabled: false
            "my-api-key": {
              "type": "text"
            }
          }
        },
        "check": {
          "type": "boolean"
        }
      }
    }
  }
}'

Upvotes: 1

Related Questions