Abyrbalg
Abyrbalg

Reputation: 13

how can I fetch only inner fields from source in ElasticSearch?

I have index structure like this:

{
          "id" : 42,
          "Person" : {
            "contracts" : [
              {
                "contractID" : "000000000000102"
              }
            ],
            "Ids" : [
              3,
              387,
              100,
              500,
              274,
              283,
              328,
              400,
              600
            ]
          },
          "dateUpdate" : "2020-12-07T13:15:00.408Z"
        }
      },
      ...
}

I need a search query that will fetch only inner "Ids" field from source and nothing more. How can I do this?

Upvotes: 1

Views: 285

Answers (1)

Bhavya
Bhavya

Reputation: 16182

You can use _source in inner_hits, in the following way

Index Mapping:

{
  "mappings": {
    "properties": {
      "Person": {
        "type": "nested"
      }
    }
  }
}

Search Query:

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "Person",
            "query": {
              "match_all": {}
            },
            "inner_hits": {
              "_source": {
                "includes": [
                  "Person.Ids"
                ]
              }
            }
          }
        }
      ]
    }
  }
}

Search Result:

"inner_hits": {
          "Person": {
            "hits": {
              "total": {
                "value": 1,
                "relation": "eq"
              },
              "max_score": 1.0,
              "hits": [
                {
                  "_index": "65237264",
                  "_type": "_doc",
                  "_id": "1",
                  "_nested": {
                    "field": "Person",
                    "offset": 0
                  },
                  "_score": 1.0,
                  "_source": {
                    "Ids": [
                      3,
                      387,
                      100,
                      500,
                      274,
                      283,
                      328,
                      400,
                      600
                    ]
                  }
                }
              ]
            }
          }
        }

You can also use nested inner_hits and _souce, in the following way

{
  "query": {
    "nested": {
      "path": "Person",
      "query": {
        "match_all": {}
      },
      "inner_hits": {
        "_source" : false,
        "docvalue_fields" : [
          {
            "field": "Person.Ids",
            "format": "use_field_mapping"
          }
        ]
      }
    }
  }
}

Upvotes: 1

Related Questions