How to perform nested queries with Elastica Search and Symfony2

前端 未结 2 1324
说谎
说谎 2021-02-11 03:13

I have a recipe entity which have some tags (many to many mapping) and I want to search recipes by tags.

Here\'s my Recipe entity:

/**
 * @ORM\\Entity
 *         


        
相关标签:
2条回答
  • 2021-02-11 03:22

    Indeed, you forgot to define the Filtered query.

    This should work :

    $nested->setQuery(new \Elastica\Query\Term(array('name' => array('value' => $searchText))));
    $nested->setPath('tags');
    $query_part->addShould($nested);
    
    $query = new \Elastica\Query\Filtered($query_part/*, $filters // in case you had other filters*/);
    return $this->find($query);
    
    0 讨论(0)
  • 2021-02-11 03:26

    Here is response how to do it. For me it works. http://obtao.com/blog/2014/04/elasticsearch-advanced-search-and-nested-objects/

    Basically, you need to create query like that:

    {
        "query":{
            "filtered":{
                "query":{
                    "query_string":{
                        "query":"*saf*"
                    }
                },
                "filter":{
                    "nested":{
                        "path":"categories",
                        "filter":{
                            "bool":{
                                "must": [{
                                    "term":{
                                        "categories.id":1
                                    }
                                }]
                            }
                        },
                        "query":{
                            "match":{
                                "id":1
                            }
                        }
                    }
                }
            }
        }
    } 
    

    For me in PHP it look like:

            $bool = new Filter\Bool();
            $bool->addMust(new Filter\Term(['categories.id' => $category->getId()]));
    
            $nested = new Filter\Nested();
            $nested->setPath("categories");
            $nested->setFilter($bool);
    
            $nested->setQuery($categoriesQuery);
    
            $queryObj = new Query\Filtered($queryObj, $nested);
    

    Filter is Elastica\Filter and Query is Elastica\Query

    0 讨论(0)
提交回复
热议问题