How to use a field's meta data in search results

My requirement is to store some meta data against some fields and retrieve them as part of search results.
Looks like the following is what I'm looking for but I'm not sure how use that in a single query.
https://www.elastic.co/guide/en/elasticsearch/reference/7.6/mapping-field-meta.html

Ex:

    PUT my_index
    {
      "mappings": {
        "properties": {
          "latency": {
            "type": "long",
            "meta": {
              "unit": "ms"
            }
          }
        }
      }
    }

I want that unit 'ms' to be added to that field in all the documents retrieved for a query.

Hi,

there are different ways to achieve this, all have pros and cons depending on what you want to do with the meta data. I assume you don't want to search on it since you want it added to all documents. One was would be to add a keyword field for this and set it to "index":false to save some space, but you would have to add the value for each document for it to show up in the "_source", e.g.

PUT my_index
{
  "mappings": {
    "properties": {
      "latency": {
        "type": "long"
      },
      "latency_unit": {
        "type": "keyword",
        "index": false
      }
      }
    }
  }
}

PUT /my_index/_doc/1
{
  "latency" : 1234567,
  "latency_unit" : "ms"
}

Of course you could also group the two fields under one parent field of type object.

If you don't want to add the same value all over in your input documents, we have a new field type called constant_keyword coming up in the next minor version (7.7) that allows you to define a field with a fixed value per index. If you want to show its value in search hits, you would need to add the field as a docvalue_fields entry in the query, e.g.

PUT my_index
{
  "mappings": {
    "properties": {
      "latency": {
        "type": "long"
      },
      "latency_unit_constant": {
        "type": "constant_keyword",
        "value": "ms"
      }
    }
  }
}

PUT /my_index/_doc/1
{
  "latency" : 1234567
}

PUT /my_index/_doc/2
{
  "latency" : 124
}

GET /my_index/_search
{
  "query": {
    "range": {
      "latency": {
        "gte": 1000
      }
    }
  },
  "docvalue_fields": [
    "latency_unit_constant"
  ]
}

Thank you for the reply/answer @cbuescher

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