Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch DSL query from an SQL statement

I'm new to Elasticsearch. I don't think I fully understand the concept of query and filters. In my case I just want to use filters as I don't want to use advance feature like scoring.

How would I convert the following SQL statement into elasticsearch query?

SELECT * FROM advertiser 
WHERE company like '%com%' 
AND sales_rep IN (1,2) 

What I have so far:

curl -XGET 'localhost:9200/advertisers/advertiser/_search?pretty=true' -d ' 
 { 
     "query" : { 
         "bool" : { 
             "must" : { 
                 "wildcard" : { "company" : "*com*" } 
             } 
         } 
     }, 
     "size":1000000 

}' 

How to I add the OR filters on sales_rep field?

Thanks

like image 650
Yada Avatar asked Dec 19 '11 18:12

Yada


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.

What is query DSL in Elasticsearch?

Elasticsearch provides a full Query DSL (Domain Specific Language) based on JSON to define queries. Think of the Query DSL as an AST (Abstract Syntax Tree) of queries, consisting of two types of clauses: Leaf query clauses.

How do I search for a query in Elasticsearch?

You can use the search API to search and aggregate data stored in Elasticsearch data streams or indices. The API's query request body parameter accepts queries written in Query DSL. The following request searches my-index-000001 using a match query. This query matches documents with a user.id value of kimchy .


1 Answers

Add a "should" clause after your must clause. In a bool query, one or more should clauses must match by default. Actually, you can set the "minimum_number_should_match" to be any number, Check out the bool query docs.

For your case, this should work.

    "should" : [
        {
            "term" : { "sales_rep_id" : "1" }
        },
        {
            "term" : { "sales_rep_id" : "2" }
        }
    ],

The same concept works for bool filters. Just change "query" to "filter". The bool filter docs are here.

like image 110
Andy Avatar answered Nov 15 '22 05:11

Andy