Home > Net >  elasticsearch: filtering out records using match
elasticsearch: filtering out records using match

Time:11-11

I have to fetch records from items index with condition that either of fields 'name' or 'description' contains 'refrigerator', but field status doesn't contain '-wip'. I have written query as:

GET items/_search
{
    "query": {
        "bool": {
            "must": {
                "multi_match": {
                    "operator": "or",
                    "fields": [
                        "name",
                        "description"
                    ],
                    "query": "refrigerator"
                }
            },
            "filter": {
                "match": {
                    "status": [
                        "-wip"
                    ]
                }
            }
        }
    }
}

But it gives me error:

failed to parse field [filter]

Seems "match" doesn't work.

How can I fetch compatible items?

CodePudding user response:

In your query syntax of "match" is wrong.

{
    "query": {
        "bool": {
            "must": {
                "multi_match": {
                    "operator": "or",
                    "fields": [
                        "name",
                        "description"
                    ],
                    "query": "refrigerator"
                }
            },
            "filter": {
                "match": {
                    "status":  "-wip" --> remove square bracket
                    
                }
            }
        }
    }
}

Above query will select documents with "status" as "wip/-wip" and having refrigerator in "name" or "description".

To exclude where status is "-wip", use "must_not" on keyword field

{
  "query": {
    "bool": {
      "must": {
        "multi_match": {
          "operator": "or",
          "fields": [
            "name",
            "description"
          ],
          "query": "refrigerator"
        }
      },
      "must_not": [
        {
          "term": {
            "status.keyword": {
              "value": "-wip"
            }
          }
        }
      ]
    }
  }
}

keyword field is used since "-wip" will be tokenized as ["-","wip"] so exact match is required.

  • Related