Nested field type

    Any object field can take an array of objects. Each of the objects in the array is dynamically mapped as an object field type and stored in flattened form. This means that the objects in the array are broken down into individual fields, and values for each field across all objects are stored together. It is sometimes necessary to use the nested type to preserve a nested object as a whole so that you can perform a search on it.

    By default, each of the nested objects is dynamically mapped as object field type. Any object field can take an array of objects.

    copy

    When these objects are stored, they are flattened, so their internal representation has an array of all values for each field:

    1. "patients.name" : ["John Doe", "Mary Major"],
    2. "patients.age" : [56, 85],
    3. "smoker" : [true, false]
    4. }

    Some queries will work correctly in this representation. If you search for patients older than 75 OR smokers, document 100 should match.

    The query correctly returns document 100:

    1. {
    2. "took" : 3,
    3. "timed_out" : false,
    4. "_shards" : {
    5. "total" : 1,
    6. "successful" : 1,
    7. "skipped" : 0,
    8. "failed" : 0
    9. },
    10. "hits" : {
    11. "total" : {
    12. "value" : 1,
    13. "relation" : "eq"
    14. },
    15. "max_score" : 1.3616575,
    16. "hits" : [
    17. "_index" : "testindex1",
    18. "_type" : "_doc",
    19. "_id" : "100",
    20. "_score" : 1.3616575,
    21. "_source" : {
    22. {
    23. "name" : "John Doe",
    24. "age" : "56",
    25. "smoker" : true
    26. },
    27. {
    28. "name" : "Mary Major",
    29. "age" : "85",
    30. "smoker" : false
    31. }
    32. ]
    33. }
    34. }
    35. ]
    36. }
    37. }

    Alternatively, if you search for patients older than 75 AND smokers, document 100 should not match.

    copy

    However, this query still incorrectly returns document 100. This is because the relation between age and smoking was lost when arrays of values for individual fields were created.

    Nested objects are stored as separate documents, and the parent object has references to its children. To mark objects as nested, create a mapping with a nested field type.

    1. PUT testindex1
    2. {
    3. "properties": {
    4. "patients": {
    5. "type" : "nested"
    6. }
    7. }
    8. }
    9. }

    Then, index a document with a nested field type:

    copy

    Now if you run the same query to search for patients older than 75 AND smokers, nothing is returned, which is correct.

    1. "took" : 3,
    2. "timed_out" : false,
    3. "_shards" : {
    4. "total" : 1,
    5. "successful" : 1,
    6. "skipped" : 0,
    7. "failed" : 0
    8. },
    9. "hits" : {
    10. "total" : {
    11. "value" : 0,
    12. "relation" : "eq"
    13. },
    14. "max_score" : null,
    15. "hits" : [ ]
    16. }

    The following table lists the parameters accepted by object field types. All parameters are optional.