【问题标题】:FOSElasticaBundle : Query matching combinaison of valuesFOS Elastica Bundle:查询匹配的值组合
【发布时间】:2020-05-15 10:31:18
【问题描述】:

我需要一些帮助才能使我的 elasticsearch 查询完全正常工作(使用版本 6.8.5)。
我的索引中存储了一个 ES 对象列表:

Object 1:  
    name: abcd
    type: A
    tags: Tag one, Tag two

Object 2:
    name: abcdef
    type: B 
    tags: Tag three

Object 3: 
    name: cdef
    type: B
    tags: Tag one, Tag three

Object 4: 
    name: abcd efgh
    type: C
    tags: Tag one, Tag three

Object 5: 
    name: efghbc
    type: A
    tags: Tag three

我需要查询:

Object.name MUST contain "bc"
AND
Object.type MUST be (A OR C)
AND
Object.tags MUST have (tag1 OR tag3)

所以我的结果应该给我:

Object 1 : match "bc" AND A type AND "tag one"
Object 4 : match "bc" AND C type AND ("tag one" AND "tag three")
Object 5 : match "bc" AND A type AND "tag three"

这是我目前的 PHP 代码:


$boolQuery = new \Elastica\Query\BoolQuery();

// ex : $q = 'bc';

if (!empty($q)) {
    $fieldQuery = new \Elastica\Query\MatchPhrasePrefix();
    $fieldQuery->setFieldQuery('name', $q);
    $fieldQuery->setFieldParam('name', 'analyzer', 'ngram_analyzer');
    $boolQuery->addShould($fieldQuery);
} else {
     $fieldQuery = new \Elastica\Query\MatchAll();
     $boolQuery->addMust($fieldQuery);
}

$subQuery = new \Elastica\Query\BoolQuery();

$typeQuery = new \Elastica\Query\Terms();
$typeQuery->setTerms('type', ['A', 'C']);
$subQuery->addMust($typeQuery);

$filterQuery = new \Elastica\Query\Terms();
$filterQuery->setTerms('tags', ['Tag one', 'Tag three']);
$subQuery->addMust($filterQuery);

$boolQuery->addMust($subQuery);
$query = new \Elastica\Query($boolQuery);

我的结果总是空的。 如果我删除 filterQuery,我的结果对应于:

Object 1 : match "bc" AND A type
Object 4 : match "bc" AND C type
Object 5 : match "bc" AND A type

我还尝试将 filterQuery 隔离在另一个布尔查询中,但没有任何结果。 谢谢!!

【问题讨论】:

  • 你能把索引脚本和数据放在问题里吗?

标签: php elastica foselasticabundle


【解决方案1】:

我终于找到了一个有效的代码。 我不得不更换这部分

$filterQuery = new \Elastica\Query\Terms();
$filterQuery->setTerms('tags', ['Tag one', 'Tag three']);
$subQuery->addMust($filterQuery);

这个

$tagFilters = ['Tag one', 'Tag three'];

$boolFilteredQuery = new \Elastica\Query\BoolQuery();
foreach($tagFilters as $tagFilter){
    $filterQuery = new \Elastica\Query\Match();
    $filterQuery->setFieldQuery('tags', $tagFilter);
    $boolFilteredQuery->addShould($filterQuery);
}
$boolQuery->addMust($boolFilteredQuery);

如果有人有解释,我很感兴趣。
谢谢

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多