使用AND运算符搜索多个单词

时间:2015-10-19 06:54:17

标签: java elasticsearch

这就像一个魅力:

        Client client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("localhost", 9300));

        FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("field", "word_1");
        fuzzyQueryBuilder.fuzziness(Fuzziness.AUTO);

        SearchResponse response = client.prepareSearch("ts_index")
                                        .setTypes("service")
                                        .setQuery(fuzzyQueryBuilder)
                                        .setFrom(0).setSize(60).setExplain(true)
                                        .execute()
                                        .actionGet();
        SearchHit[] results = response.getHits().getHits();

但如果我想用多个单词进行搜索,则不会返回任何内容,例如:

FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("field", "word_1 word_2");

当我使用 CURL 时,我已通过将<{1}}添加到 JSON 属性来解决此问题:

  

curl -XGET“http://localhost:9200/_search” - d“{\”query \“:{\”match \“:{\”field \“:{\”query \“:\”word_1 word_2 \“ ,\ “模糊\”:\ “AUTO \”,\ “操作符\”:\ “和\”}}}}

如何在Java中实现这一目标?

2 个答案:

答案 0 :(得分:2)

我认为,对于AND,must和对于OR:{/ 1> should,这是可能的

 QueryBuilder qb = QueryBuilders.boolQuery()
                .must(QueryBuilders.fuzzyQuery("field", "word_1"))
                .must(QueryBuilders.fuzzyQuery("field", "word_2"));

答案 1 :(得分:1)

您可以尝试使用enum

以动态方式构建此内容
 public enum MultiQueryBuilder {

  OPERATOR_AND {
    @Override
    public QueryBuilders createQuery(String field, String multiWord) {
    String[] words = multiWord.split("\\s+");
    QueryBuilder queryBuilder = QueryBuilder.boolQuery();
    for(String word : words){
     queryBuilder.must(QueryBuilders.fuzzyQuery(field, word));
    }    
    return queryBuilder;
},

 OPERATOR_OR {
    @Override
    public QueryBuilders createQuery(String field, String multiWord) {
    String[] words = multiWord.split("\\s+");
    QueryBuilder queryBuilder = QueryBuilder.boolQuery();
    for(String word : words){
     queryBuilder.should(QueryBuilders.fuzzyQuery(field, word));
    }    
 return queryBuilder;
};

 public abstract Querybuilders createQuery(String field, String multiWord);
}

你只需要这样打电话:

FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders
    .fuzzyQuery(MultiQuerybuilder
    .valueOf(OPERATOR_AND)
    .createQuery("field", "word_1 word_2"));