Search code examples
scalaelasticsearchelasticsearch-query

Scala Elasticsearch query with multiple parameters


I need to delete certain entries from an Elasticsearch table. I cannot find any hints in the documentation. I'm also an Elasticsearch noob. The to be deleted rows will be identified by its type and an owner_id. Is it possible to call deleteByQuery with multiple parameters? Or any alternatives to reach the same?

I'm using this library: https://github.com/sksamuel/elastic4s

How the table looks like:

| id |  type | owner_id | cost |
|------------------------------|
| 1  | house |    1     | 10   |
| 2  | hut   |    1     | 3    |
| 3  | house |    2     | 16   |
| 4  | house |    1     | 11   |

In the code it looks like this currently:

deleteByQuery(someIndex, matchQuery("type", "house"))

and I would need something like this:

deleteByQuery(someIndex, matchQuery("type", "house"), matchQuery("owner_id", 1))

But this won't work since deleteByQuery only accepts a single Query.

In this example it should delete the entries with id 1 and 4.


Solution

  • Explaining it in JSON and rest API format, to make it more clear.

    Index Sample documents

    put myindex/_doc/1
    {
      "type" : "house",
      "owner_id" :1
      
    }
    
    put myindex/_doc/2
    {
      "type" : "hut",
      "owner_id" :1
      
    }
    
    put myindex/_doc/3
    {
      "type" : "house",
      "owner_id" :2
      
    }
    
    put myindex/_doc/4
    {
      "type" : "house",
      "owner_id" :1
      
    }
    

    Search using the boolean query

    GET myindex/_search
    {
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "type": "house"
              }
            }
          ],
          "filter": [
            {
              "term": {
                "owner_id": 1
              }
            }
          ]
        }
      }
    }
    

    And query result

     "hits" : [
          {
            "_index" : "myindex",
            "_type" : "_doc",
            "_id" : "1",
            "_score" : 0.35667494,
            "_source" : {
              "type" : "house",
              "owner_id" : 1
            }
          },
          {
            "_index" : "myindex",
            "_type" : "_doc",
            "_id" : "4",
            "_score" : 0.35667494,
            "_source" : {
              "type" : "house",
              "owner_id" : 1
            }
          }
        ]