Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL "not in" Query in Elasticsearch

I want to achieve something like this SELECT * FROM myindex where _id not in (1, 2, 3) in Elasticsearch. One way to do this is:

{
    "from": 0,
    "size": 200,
    "query": {
        "bool": {
            "must": {
                "bool": {
                    "must_not": {
                        "bool": {
                            "should": [
                                {
                                    "match": {
                                        "_id": {
                                            "query": 1,
                                            "type": "phrase"
                                        }
                                    }
                                },
                                {
                                    "match": {
                                        "_id": {
                                            "query": 2,
                                            "type": "phrase"
                                        }
                                    }
                                },
                                {
                                    "match": {
                                        "_id": {
                                            "query": 3,
                                            "type": "phrase"
                                        }
                                    }
                                }
                            ]
                        }
                    }
                }
            }
        }
    }
}

But this approach wouldn't scale for a big array because this will be a huge query. Is there a better way to do this?

like image 993
Amit Tripathi Avatar asked Mar 07 '17 10:03

Amit Tripathi


People also ask

Can you query Elasticsearch with SQL?

Use your SQL skills to query data within Elasticsearch, harnessing the power of Elastic with a familiar language. Send your SQL queries via a CLI, REST endpoint, ODBC, or JDBC to get your results with newfound speed.

Is Elasticsearch a SQL database?

Completely open source and built with Java, Elasticsearch is a NoSQL database. That means it stores data in an unstructured way and that you cannot use SQL to query it.

What is terms in Elasticsearch?

Elasticsearch provides a way to find a document containing a precise match of a specified term in a document field. Using term and terms query API, you can find documents that match accurate values within a specified field. Let us learn how to use the term and terms queries in Elasticsearch.


1 Answers

Maybe something like this?

GET _search
{
  "query" : {
    "bool" : {
      "must_not" : {
        "terms" : {
          "_id" : [1,2,3]
        }
      }
    }
  }
}
like image 97
barat Avatar answered Oct 26 '22 06:10

barat