Search code examples
elasticsearchelasticsearch-dsl

Elasticsearch query syntax


I have a index with a mapping as follows

  "mappings": {
    "properties": {
      "name": {
        "type": "text"
      },
      "id": {
        "type": "integer"
      },
      "is_active": {
        "type": "boolean"
      },
      "attributes": {
        "dynamic": true,
        "properties": {
          "subjects": {
            "type": "integer"
          },
          "occupation": {
            "type": "integer"
          }
        }

Now I want to get all documents with occupation =4 and name not like 'Test' and is_active = True I have written following to get all documents with is_active=True and occupation 4, but I am not sure how to filter out documents where name contains 'test'

{
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "should": [
              {
                "terms": {
                  "audience_attributes.occupation": [
                    4
                  ]
                }
              }
            ]
          }
        },
        {
          "terms": {
            "is_active": [
              true
            ]
          }
        }
      ]
    }
  }
}

I am using Elasticsearch 7.9


Solution

  • I think I got it

    {
      "query": {
        "bool": {
          "must_not": {
            "wildcard": {
              "name": {
                "value": "*TEST*"
              }
            }
          },
          "must": [
            {
              "bool": {
                "should": [
                  {
                    "terms": {
                      "audience_attributes.occupation": [
                        4
                      ]
                    }
                  }
                ]
              }
            },
            {
              "terms": {
                "is_active": [
                  true
                ]
              }
            }
          ]
        }
      }
    }