Search code examples
elasticsearchelastic-stackelasticsearch-5

Elastic Search - check if array of strings has any string that starts with word "cake"


These are my fields:

      {"brand" : "A",
      "productType" : "food",
      "infoList" : [
        "pizza-34","cake-qaw-34"
      ]},
      {
       "brand" : "B",
      "productType" : "food",
      "infoList" : [
        "pasta-3"
      ]}

I want only those documents to be returned which begin with the word "cake" anywhere in their infoList. In this case, I should get this

{"brand" : "A",
          "productType" : "food",
          "infoList" : [
            "pizza-34","cake-qaw-34"
          ]}

Can someone tell how to achieve this?
PS: Cannot use regexp for this


Solution

  • You can use prefix query to get those documents whose array of strings has any string that starts with the word “cake”

    {
      "query": {
        "prefix": {
          "infoList": "cake"
        }
      }
    }
    

    Search Result will be

    "hits": [
          {
            "_index": "67778291",
            "_type": "_doc",
            "_id": "1",
            "_score": 1.0,
            "_source": {
              "brand": "A",
              "productType": "food",
              "infoList": [
                "pizza-34",
                "cake-qaw-34"
              ]
            }
          }
        ]
    

    Update 1:

    {
      "query": {
        "bool": {
          "must_not": {
            "prefix": {
              "infoList": "cake"
            }
          }
        }
      }
    }
    

    Search Result will be

    "hits": [
          {
            "_index": "67778291",
            "_type": "_doc",
            "_id": "2",
            "_score": 0.0,
            "_source": {
              "brand": "B",
              "productType": "food",
              "infoList": [
                "pasta-3"
              ]
            }
          }
        ]