khairul
khairul

Reputation: 33

Filter document on items in an array ElasticSearch using Where In

I have data:

[
  {
    "NAME": "John Doe", 
    "CLASS":[1,10,30]
  },
  {
    "NAME": "Albert",
    "CLASS": [1,20,40]
  },
  {
    "NAME": "XINN",
    "CLASS": [10,30]
  },
  {
    "NAME": "UJANG",
    "CLASS": [20,40]
  },
  {
    "NAME": "BAMBANG",
    "CLASS": [30,40]
  }
]

I have the following query SQL:

SELECT * FROM table_name WHERE CLASS IN (1,20)

and I want what will appear is:

[{"NAME": "John Doe","CLASS":[1,10,30]},{"NAME": "Albert","CLASS": [1,20,40]},{"NAME": "UJANG","CLASS": [20,40]}]

How do I change my search to match the SQL query?

Upvotes: 1

Views: 114

Answers (1)

Amit
Amit

Reputation: 32386

You can use the terms query to get your expected results, adding a working example.

Index sample docs

{
    "name" : "John Doe",
    "class" : [1, 10,30]
}

{
    "name": "Albert",
    "class": [1,20,40]
}

{
    "name": "XINN",
    "class": [10,30]
}

{
    "name": "UJANG",
    "class": [20,40]
}

{
    "name": "BAMBANG",
    "class": [30,40]
}

And search query

{
    "query": {
        "terms": {
            "class": [
                1,20
            ]
        }
    }
}

And search results

"hits": [
            {
                "_index": "shingleside",
                "_type": "_doc",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "name": "John Doe",
                    "class": [
                        1,
                        10,
                        30
                    ]
                }
            },
            {
                "_index": "shingleside",
                "_type": "_doc",
                "_id": "2",
                "_score": 1.0,
                "_source": {
                    "name": "Albert",
                    "class": [
                        1,
                        20,
                        40
                    ]
                }
            },
            {
                "_index": "shingleside",
                "_type": "_doc",
                "_id": "4",
                "_score": 1.0,
                "_source": {
                    "name": "UJANG",
                    "class": [
                        20,
                        40
                    ]
                }
            }
        ]

Upvotes: 1

Related Questions