foselasticabundle嵌套查询

时间:2016-10-14 02:03:35

标签: symfony elasticsearch elastica foselasticabundle

我使用FOSElasticaBundle将我的symfony3项目与elasticsearch集成。我的映射类似于:

company:
    mappings:
        id: { boost: 1, type: string, index: not_analyzed }
        cik: { boost: 2, type: string, index: not_analyzed }
        conformedName: { boost: 6, analyzer: custom_analyzer }
        assignedSIC:
            type: object
            properties:
                id: { type: string, index: not_analyzed }
                code: { type: string, index: not_analyzed }
                title: { analyzer: custom_analyzer }
        businessAddress:
            type: object
            properties:
                street1: { analyzer: custom_analyzer }
                street2: { analyzer: custom_analyzer }
                city: { analyzer: custom_analyzer }
                state: { analyzer: custom_analyzer }
                zip: { type: string, index: not_analyzed }
                phone: { type: string, index: not_analyzed }

我想按嵌套的businessAddress属性的city,state和zip进行过滤。

我有这个问题:

$boolQuery = new BoolQuery();
$cityQuery = new Match();
$cityQuery->setFieldQuery('businessAddress.city', array($city]));
$cityQuery->setFieldParam('businessAddress.city', 'analyzer', 'custom_analyzer');
$boolQuery->addMust($cityQuery);
$this->finder->find($boolQuery);

json查询为

{"query":{"bool":{"must":[{"match":{"businessAddress.city":{‌​"query":["NY"],"anal‌​yzer":"custom_analyz‌​er"}}}]}}}

但是有0个结果,我不知道sintax businessAddress.city是否会被bundle自动处理,还是我需要创建一个嵌套查询。如果是嵌套查询我怎么能​​构建它?

修改

在下面的一些评论后,我注意到我将匹配术语设置为数组,现在我改为:

$cityQuery->setFieldQuery('businessAddress.city', array($city]));

$cityQuery->setFieldQuery('businessAddress.city', $city]);

导致json查询:

{"query":{"bool":{"must":[{"match":{"businessAddress.state":{"query":"NY","analyzer":"custom_analyzer"}}}]}}}

我已通过互联网查询,一无所获。

请帮忙。感谢

1 个答案:

答案 0 :(得分:0)

以下是如何使用嵌套查询实现它。

首先,您需要更新映射,以使businessAddress成为nested

类型
...
    businessAddress:
        type: nested
...

然后,您将能够执行以下Nested查询

$boolQuery = new BoolQuery();
$cityQuery = new Match();
$cityQuery->setFieldQuery('businessAddress.city', array($city]));
$cityQuery->setFieldParam('businessAddress.city', 'analyzer', 'custom_analyzer');
$boolQuery->addMust($cityQuery);
// nested query
$query = new Nested();
$query->setPath('businessAddress');
$query->setQuery($boolQuery);
// pass the nested query to your finder
$this->finder->find($query);

希望这有帮助