Can I query a non-indexed field using a runtime field?

If I create a mapping that doesn't index any fields:

PUT test-index/
{
  "mappings": {
   "dynamic": false
  }
}

and then add a document

POST test-index/_doc
{
  "a": "a",
  "b": "b",
  "c": "c"
}

Can I then use a dynamic field to query the _source of the document? This is what I'm trying:

GET test-index/_search
{
  "runtime_mappings": {
    "runtime-a": {
      "type": "keyword",
      "script": {
        "source": "ctx._source.a"
      }
    }
  },
  
  "query": {
    "term": {
      "runtime-a": "a"
    }
  }
}

But it's returning the error:

"error" : {
    "root_cause" : [
      {
        "type" : "script_exception",
        "reason" : "compile error",
        "script_stack" : [
          "ctx._source.a",
          "           ^---- HERE"
        ],
  ....

This is not the right so called script context to use. This should work:

POST test-index/_doc
{
  "a": "a",
  "b": "b",
  "c": "c"
}

GET test-index/_search
{
  "runtime_mappings": {
    "runtime-a": {
      "type": "keyword",
      "script": {
        "source": "emit(doc['a.keyword'].value)"
      }
    }
  },
  
  "query": {
    "term": {
      "runtime-a": "a"
    }
  }
}

Hope this helps!

1 Like

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