简体   繁体   中英

Elastic Search query string exclude field from search scoring

I am trying to exclude a certain field from being scored in when using Elastic Search, using the Java API.

For example, two documents:

{
   "id": 1,
   "bar": "foo",
   "exclude_this": "filler"
},
{
   "id": 2,
   "bar": "different",
   "exclude_this": "something else"
}

Currently, I am constructing the query like this:

    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    boolQueryBuilder.must(QueryBuilders.queryStringQuery(query)
        .defaultOperator(Operator.AND));

Where query is some ElasticSearch query string. Needless to say, I do not want exclude_this to affect search results. However, if for example String query = "filler" , then I don't want the object 1 showing up - in that case, I want nothing to match. I tried to use the fields method, which was recommended in the documentation as the way to accomplish this:

Map<String, Float> fieldsToQuery = new HashMap<>();
fieldsToQuery.put("bar", 1f);
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(QueryBuilders.queryStringQuery(query)
    .defaultOperator(Operator.AND))
    .fields(fieldsToQuery);

However after doing this, on everything except wildcard searches, I get no results from searches; even when String query = "foo" , then I will get nothing, as if every field is being excluded.

Any help?

To my opinion if I understand correct what you want, this is something you could use:

BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(QueryBuilders
                        .multiMatchQuery("search text", "bar", "id")
                        .operator(Operator.AND)
                 );
boolQueryBuilder.mustNot(QueryBuilders
                        .matchQuery("exclude_this", "search text")
                        .operator(Operator.AND)
                 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM