Dynamic template copy_to does not work with flattened type

I have a field of flattened type that contains a subfield that I want to do numeric range searches on. I am trying to use a dynamic template to copy the field's value to a top level field that I can use for range queries and sorting but it's not working.

Here is a simplified version of the template:

{
    "mappings": {
        "dynamic_templates": [
            {
                "age_as_long": {
                    "path_match": "person.age",
                    "mapping": {
                        "type": "long",
                        "copy_to": "personAge"
                    }
                }
            }
        ],
        "properties": {
            "id": {
                "type": "keyword"
            },
            "person": {
                "type": "flattened"
            }
        }
    }
}

With an example doc

{
    "id": "123",
	"person": {
		"name": "jim",
		"age": 30
	}
}

I would expect the following query to return the doc but it doesn't

{
    "query": {
        "range": {
            "personAge": {
                "gte": 20,
                "lte": 40
            }
        }
    }
}

Is this expected behaviour or is it a bug?

Elasticsearch version: 8.3.2

that may not work using flattened field type. considering moving person.age to its own field. However you can use runtime fields. here is what worked for me using your mapping and docs

GET /suntest3/_search
{
  "runtime_mappings": {
    "personAge": {
      "type": "long",
      "script": {
        "source": """
        if (doc.containsKey('person.age')) {
          String ageString = doc['person.age'].value;
          if (ageString != null && !ageString.isEmpty()) {
            long age = Long.parseLong(ageString);
            emit(age);
          }
        }
        """
      }
    }
  },
  "query": {
    "range": {
      "personAge": {
        "gte": 20,
        "lte": 40
      }
    }
  }
}

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