Home > Enterprise >  Do not retrieve all columns with Elastic search query
Do not retrieve all columns with Elastic search query

Time:07-26

I have an Elastic search query and I would like to retrieve a certain column, not all.

I make my request in java with BoolQUEryBuilder which gives:

BoolQueryBuilder query = boolQuery();
query.must(wildcardQuery('value', value   "*"));
return findAll(query);

The method findAll :

protected List<T> findAll(final BoolQueryBuilder query) {
    Query searchQuery = (new NativeSearchQueryBuilder()).withQuery(query).build();
    SearchHits<T> searchHits = this.elasticsearchRestTemplate.search(searchQuery, this.getClazz(), this.elasticsearchRestTemplate.getIndexCoordinatesFor(this.getClazz()));
    return (List)SearchHitSupport.unwrapSearchHits(searchHits);
}

I would like to add a filter on the columns. To illustrate in SQL this gives:

Select column_one, column_two from table;

CodePudding user response:

With Spring Data Elasticsearch, you should try this instead:

...

//include only specific fields
final SourceFilter sourceFilter = new FetchSourceFilter(new String[]{"column_one", "column_two"}, null);

// assemble the query
Query searchQuery = new NativeSearchQueryBuilder().withQuery(query).build();        
searchQuery.addSourceFilter(sourceFilter);

...

CodePudding user response:

Refer source filtering to fetch only few fields from Elasticsearch query results.

As explained in the same document example below code shows which fields to include and which to exclude.

String[] includeFields = new String[] {"title", "innerObject.*"};
String[] excludeFields = new String[] {"user"};
sourceBuilder.fetchSource(includeFields, excludeFields);
  • Related