Mandeep Singh
Mandeep Singh

Reputation: 8234

Elasticsearch: How to make all properties of object type as non analyzed?

I need to create an Elasticsearch mapping with an Object field whose keys are not known in advance. Also, the values can be integers or strings. But I want the values to be stored as non analyzed fields if they are strings. I tried the following mapping:

PUT /my_index/_mapping/test
{
  "properties": {
    "alert_text": {
      "type": "object",
      "index": "not_analyzed"
    }
  }
}

Now the index is created fine. But if I insert values like this:

POST /my_index/test
{
  "alert_text": {
    "1": "hello moto"
  }
}

The value "hello moto" is stored as an analyzed field using standard analyzer. I want it to be stored as a non analyzed field. Is it possible if I don't know in advance what all keys can be present ?

Upvotes: 4

Views: 4606

Answers (1)

moliware
moliware

Reputation: 10278

Try dynamic templates. With this feature you can configure a set of rules for the fields that are created dynamically.

In this example I've configured the rule that I think you need, i.e, all the strings fields within alert_text are not_analyzed:

PUT /my_index
{
    "mappings": {
        "test": {
            "properties": {
                "alert_text": {
                  "type": "object"   
                }
            },
            "dynamic_templates": [
                {
                    "alert_text_strings": {
                        "path_match": "alert_text.*", 
                        "match_mapping_type": "string",
                        "mapping": {
                            "type": "string",
                            "index": "not_analyzed"
                        }
                    }
                }
            ]
        }
    }
}

POST /my_index/test
{
  "alert_text": {
    "1": "hello moto"
  }
}

After executing the requests above you can execute this query to show the current mapping:

GET /my_index/_mapping

And you will obtain:

{
   "my_index": {
      "mappings": {
         "test": {
            "dynamic_templates": [
               {
                  "alert_text_strings": {
                     "mapping": {
                        "index": "not_analyzed",
                        "type": "string"
                     },
                     "match_mapping_type": "string",
                     "path_match": "alert_text.*"
                  }
               }
            ],
            "properties": {
               "alert_text": {
                  "properties": {
                     "1": {
                        "type": "string",
                        "index": "not_analyzed"
                     }
                  }
               }
            }
         }
      }
   }
}

Where you can see that alert_text.1 is stored as not_analyzed.

Upvotes: 6

Related Questions