如何使用ElasticSearch Java API构建具有可变match()子句数的查询

14ifxucb  于 2023-01-08  发布在  ElasticSearch
关注(0)|答案(1)|浏览(117)

我想根据3个字段值的组合检索文档:

  • 规范形式
  • 文法
  • 意义

我现在是这么做的。

String canonicalForm = "tut";
String grammar = "verb";
String meaning = "to land";

BoolQuery bool = BoolQuery.of(q -> q
            .must(m -> m
                .match(mt -> mt
                    .field("descr.canonicalForm")
                        .query(canonicalForm)
                    )
            )
            .must(m -> m
                .match(mt -> mt
                    .field("descr.grammar")
                        .query(grammar)
                    )
            )
            .must(m -> m
                .match(mt -> mt
                    .field("descr.meaning")
                        .query(meaning)
                    )
            )
        );

只要我为所有三个字段提供一个值,这就可以工作。但是有时我想只使用其中的一两个字段进行搜索。
我尝试将“absent”字段值设置为null,但这引发了一个异常。
我还尝试将“absent”值设置为空字符串,但总是返回0个匹配项。
另一种解决方案是仅在提供的值不为空时为字段添加match()子句,但我不知道如何在Fluent DSL构建器模式中插入这种条件。

6yoyoihd

6yoyoihd1#

我相信您必须使用should clausule

BoolQuery bool = BoolQuery.of(q -> q
        .should(m -> m
            .match(mt -> mt
                .field("descr.canonicalForm")
                .query("canonicalForm")
            )
        )
        .should(m -> m
            .match(mt -> mt
                .field("descr.grammar")
                .query("grammar")
            )
        )
        .should(m -> m
            .match(mt -> mt
                .field("descr.meaning")
                .query("meaning")
            )
        )
        .minimumShouldMatch("1")
    );

相关问题