How can I query each field?

Viewed 30
  • Sample document
{
    "_id": "1",
    "DOC": [
        {
            "key": "A B C"
        },
        {
            "key": "B C D"
        },
        {
            "key": "C D E"
        }
    ]
}

I want to highlight document's each key having A and C.

But all queries I've tried search whole documents.

If I search A and C, they give me

"highlight": {
    "DOC.key": [
        "<keyword>A</keyword> B <keyword>C</keyword>",
        "B <keyword>C</keyword> D",
        "<keyword>C</keyword> D E"
    ]
}

"<keyword>A</keyword> B <keyword>C</keyword>" is correct.

But I didn't want "B <keyword>C</keyword> D" and "<keyword>C</keyword> D E".

I want to highlight key which have A with C

"highlight": {
    "DOC.key": [
        "<keyword>A</keyword> B <keyword>C</keyword>"
    ]
}

How can I search it?

1 Answers

Normal arrays are flattened in elastic search. So after indexing document has no idea that all "keys" are separate.

If you want to treat each "key" as separate entity, you need to declare it as nested

Mapping

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

Query

{
  "query": {
    "nested": {
      "path": "DOC",
      "query": {
        "match": {
          "DOC.key": {
            "query": "A C",
            "operator": "and"
          }
        }
      },
      "inner_hits": {
        "highlight": {
          "fields": {
            "DOC.key": {}
          }
        }
      }
    }
  }
}

Result

{
        "_index" : "index61",
        "_type" : "_doc",
        "_id" : "QUI7Dn0BLZ9gNW_AS1dp",
        "_score" : 1.1037275,
        "_source" : {
          "DOC" : [
            {
              "key" : "A B C"
            },
            {
              "key" : "B C D"
            },
            {
              "key" : "C D E"
            }
          ]
        },
        "inner_hits" : {
          "DOC" : {
            "hits" : {
              "total" : {
                "value" : 1,
                "relation" : "eq"
              },
              "max_score" : 1.1037275,
              "hits" : [
                {
                  "_index" : "index61",
                  "_type" : "_doc",
                  "_id" : "QUI7Dn0BLZ9gNW_AS1dp",
                  "_nested" : {
                    "field" : "DOC",
                    "offset" : 0
                  },
                  "_score" : 1.1037275,
                  "_source" : {
                    "key" : "A B C"
                  },
                  "highlight" : {
                    "DOC.key" : [
                      "<em>A</em> B <em>C</em>"
                    ]
                  }
                }
              ]
            }
          }
        }
      }
Related