cakephp / elastic-search

Elastic search datasource for CakePHP
Other
88 stars 53 forks source link

Basic Search Query #146

Closed ghost closed 6 years ago

ghost commented 6 years ago

How do I build a query like below by find() method?

{
  "query": {
    "query_string": {
      "fields": ["title","body"],
      "query": "keyword1 keyword2"
    }
  }
}

If I write something like below in my controller,

$search_result = $this->ElasticArticles->find()
    ->where([
        'or' => [
            'title' => 'keyword1 keyword2',
            'body' => 'keyword1 keyword2'
        ]
    ]);

I get queries like this

"query" : {
    "bool" : {
        "filter" : [{
            "bool" : {
                "must" : [{
                    "bool" : {
                        "should" : [{ 
                            "term" : {
                                "title" : "keyword1 keyword2"
                             }
                          },
                          {
                              "term" : {
                                  "body" : "keyword1 keyword2" 
                               } 
                          }]
                       }
                   }]
               }
           }]
       }
    }

I would like to search indices by two keywords that match the contents of the title or the body.

I use elasticsearch6.2.2 and cakephp/elastic-search2.0 beta

Thanks in advance.

lorenzo commented 6 years ago

Use the QueryBuilder object as described here:

https://book.cakephp.org/3.0/en/elasticsearch.html#searching-indexed-documents

You can use, for example, the simpleQueryString method:

https://github.com/cakephp/elastic-search/blob/master/src/QueryBuilder.php#L437

ghost commented 6 years ago

It worked as expected! Thank you so much!