Need to add doc to an index with default values

Suppose i have an index with 2 fields as
firstname and lastname both having default values as "test"

Now if I insert a new record in that index
POST my-index-000001/general
{
"firstname": "harry",
"lastname": "potter"
}
and then
POST my-index-000001/general
{
"firstname": "harry1"
}

If i do GET my-index-000001/_search
I should get 2 records with 2nd record having lastname as "test.
How to achieve this?
Please help

You are using the null_value parameter on your field mapping, right?

Check this code following your example:

# Create the index
PUT my-index-000001/
{
  "mappings": {
    "dynamic": false,
    "properties": {
      "firstname": {
        "type": "keyword",
        "null_value": "test"
      },
      "secondname": {
        "type": "keyword",
        "null_value": "test"
      }
    }
  }
}

# Add a document
POST my-index-000001/_doc/1
{
"firstname": "harry",
"secondname": "potter"
}

# Add another document without
POST my-index-000001/_doc/2
{
"firstname": "hermione",
"secondname": null
}

POST my-index-000001/_doc/3
{
"firstname": "ron"
}

GET my-index-000001/_search
{
  "fields": [
    "firstname",
    "secondname"
  ], 
  "query": {
    "term": {
      "secondname": "test" 
    }
  },
  "_source": false
}

The last search returns only the hemione document

...
    "hits" : [
      {
        "_index" : "my-index-000001",
        "_id" : "2",
        "_score" : 0.6931471,
        "fields" : {
          "secondname" : [
            "test"
          ],
          "firstname" : [
            "hermione"
          ]
        }
      }
    ]
...

The catch is the last note in the null_value documentation

The null_value only influences how data is indexed, it doesn’t modify the _source document.

So your _source is not mdified, and you need to add the fields parameter to your search to get your default indexed value, check the docs.

Also you need the field to be added, that's why the result does not show ron document. If you want to avoid to add the null value you can use an ingest pipeline with the set processor (and an if condition) or a script processor.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.