elasticsearchkibanaelasticsearch-mapping

Right way to handle nested objects with type "nested"


I have an array field with type "nested". In this field i have multiple objects. This is JSON example:

{
  "users" : [
    {
      "first" : "John",
      "last" :  "Smith"
    },
    {
      "first" : "Alice",
      "last" :  "White"
    }
  ]
}

I expect the same structure after indexing. This is part of my mapping:

},
"users": {
    "dynamic": false,
    "type": "nested",
    "properties": {
        "first": {
            "type": "text"
         },
         "last": {
             "type": "text"
        },
    }
}

But after indexing i get this structure: enter image description here

    
users
    
[
  {
    "first": [
      "John"
    ],
    "last": [
      "Smith"
    ],
  },
  {
    "first": [
      "Alice"
    ],
    "last": [
      "White"
    ],
  },]

What i am doing wrong? Is this behavior expected? How i can handle nested objects?

I need only text fields, not text fields in array. Search works fine, but data format after mapping is confusing.

Delete indexes, change mapping, refresh indexes. Set dynamic: true and false. Change field types.


Solution

  • It's working as expected for me. I'm using ES v8.

    enter image description here

    PUT my-index-000001
    {
      "mappings": {
        "properties": {
          "users": {
            "dynamic": false,
            "type": "nested",
            "properties": {
              "first": {
                "type": "text"
              },
              "last": {
                "type": "text"
              }
            }
          }
        }
      }
    }
    

    PUT my-index-000001/_doc/1
    {
      "group" : "fans",
      "users" : [
        {
          "first" : "John",
          "last" :  "Smith"
        },
        {
          "first" : "Alice",
          "last" :  "White"
        }
      ]
    }
    

    GET my-index-000001/_search
    {
      "query": {
        "nested": {
          "path": "users",
          "query": {
            "bool": {
              "must": [
                { "match": { "users.first": "Alice" }},
                { "match": { "users.last":  "White" }} 
              ]
            }
          }
        }
      }
    }