Prepare SearchRequest for exact search on multiple fields [Java]

I want to form a search request for exact match on multiple fields. Now match query returns all matches whereas term query does the search on inverted index.

	SearchRequest searchRequest = new SearchRequest(ES_INDEX);
	SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

	BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
	QueryBuilder typeTerm = QueryBuilders.termsQuery("info.type", type);
	queryBuilder.must(typeTerm);
	
	searchSourceBuilder.query(matchQueryBuilder);
	
	searchRequest.source(searchSourceBuilder);
    	SearchResponse searchResponse = restHighLevelClient.search(searchRequest);

Must it match the same exact term on all fields or at least the exact term on one field ?

If the later, I'd use a keyword data type on the fields and a multimatch query.

1 Like

There could be a case I need to form multi word query and on some query I need exact search whereas on others I need full text search.

You can index the same content once with a text field and once with a keyword field.
Then you can choose at search time on which fields you want to search.

Can you please provide me an example. I tried it with Keyword data type but things don't seem to be working.

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Questionnaire extends Event {
	public Questionnaire() {
		super();
	}

	@JsonProperty("id")
	private String id;

	@JsonProperty("type")
	@Field(type = FieldType.Keyword)
	private String type;
	
	@JsonProperty("level")
	@Field(type = FieldType.Keyword)
	private Integer level;
	
	@JsonProperty("category")
	@Field(type = FieldType.Keyword)
	private List<String> category = null;

Below is the query :-

        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
	QueryBuilder typeTerm = QueryBuilders.matchQuery("questionnaire.type", type);
	queryBuilder.must(typeTerm);
        searchSourceBuilder.query(queryBuilder);
        searchRequest.source(searchSourceBuilder);

I edited your post to make it readable. Please format your code either with markdown format or by using the </> icon.

Are you using Hibernate Search? Wondering this because of:

@Field(type = FieldType.Keyword)

If you want to be able to search type with both Full Text search and Exact search, you need to index it like:

PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "type": {
          "type": "text",
          "fields": {
            "raw": { 
              "type":  "keyword"
            }
          }
        }
      }
    }
  }
}

Then if you search on type, it will be a full text search. If you search on type.raw it will be an exact search.

No I am not using Hibernate.

It's basically Spring boot application.

How does this work?

@Field(type = FieldType.Keyword)

Are you sure it is generating the right mapping in Elasticsearch?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.