Search code examples
apacheelasticsearchluceneelasticsearch-plugin

Not getting intended output on querying on a list in ElasticSearch


======== Tried below to query on a list, but didn’t work=============
Input record:

{
  "somerecord": [
    {
      "fieldValue": "1",
      "sampleKey": [
        "1",
        "2"
      ]
    },
    {
      "fieldValue": "2",
      "sampleKey": [
        "3",
        "4"
      ]
    }
  ]
}

Output expected or needed for “fieldValue”:”1” search:

{
  "fieldValue": "1",
  "sampleKey": [
    "1",
    "2"
  ]
}

Steps:
Created a mapping
Put a record
Query using different query types

References:

http://www.spacevatican.org/2012/6/3/fun-with-elasticsearch-s-children-and-nested-documents/ https://www.elastic.co/guide/en/elasticsearch/guide/current/nested-mapping.html https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html https://gist.github.com/nicolashery/6317643 http://elasticsearch-cheatsheet.jolicode.com/ http://obtao.com/blog/2014/04/elasticsearch-advanced-search-and-nested-objects/ http://joelabrahamsson.com/elasticsearch-nested-mapping-and-filter/

Please let me know how to achieve what I intent to.

======== Some of command runs =========
1.

curl -XPOST https://someClusterURL/tax2 -d '{
  "mappings": {
    "ids": {
      "properties": {
        "somerecord": {
          "type": "nested",
          "properties": {
            "fieldValue": {
              "type": "string"
            }
          }
        }
      }
    }
  }
}'
  1. curl -XPUT https://someClusterURL/tax2/ids/1 -d '{
      "somerecord": [
        {
          "fieldValue": "1",
          "sampleKey": [
            "1",
            "2"
          ]
        },
        {
          "fieldValue": "2",
          "sampleKey": [
            "3",
            "4"
          ]
        }
      ]
    }'
    
  2. 3.
curl -XGET  https://someClusterURL/tax2/ids/_search -d '{
  "query": {
    "nested": {
      "path": "somerecord",
      "query": {
        "bool": {
          "must": [
            { "match": { "fieldValue": "1" }}
          ]
        }
      }
    }
  }
}'

Result:

{
  "somerecord": [
    {
      "fieldValue": "1",
      "sampleKey": [
        "1",
        "2"
      ]
    },
    {
      "fieldValue": "2",
      "sampleKey": [
        "3",
        "4"
      ]
    }
  ]
}

Tried more, but still didn’t work.


Solution

  • Use Inner_Hits and Source Filtering (to disable source) like:

    {
    "_source": false,
    "query": {
    "nested": {
      "path": "somerecord",
      "query": {
        "bool": {
          "must": [
            { "match": { "fieldValue": "1" }}
           ]
        }
       },
       "inner_hits" :{}
       }
     }
    

    Using "_source": false will not fetch the source details.