简体   繁体   中英

How to return one field from a query (Spring Data Elasticsearch)

I am writing a query; in Kibana it's easy

GET populationstreamassignment/_search
{
    "query": {
    "match": {
      "healthyChildrenIndicator": true
    }
  }, 
  "_source": "memberId"
}

What I want to do is get a list of all the memberId's for 'healthy children'. But I want to translate this to java syntax.

import java.util.List;
import java.util.UUID;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

/**
 Spring Data Elasticsearch repository for the {@link PopulationStreamAssignment} entity.
 */
public interface PopulationStreamAssignmentSearchRepository extends ElasticsearchRepository<PopulationStreamAssignment, Long> {

    @Query("{\"match\": {\"?0\": \"?1\"}}")
    List<UUID> getMemberIdsByPopulationStream(String popStream, Boolean criteria);

}

This query has a few problems. Here is where I have questions..

  1. How can I specify "_source" so that I only return the memberId field?
  2. memberId is a UUID, can I have it directly return memberId's as a List of Values?

As mentioned in this GitHub issue, you can not directly filter source using annotation and you need to use NativeSearchQueryBuilder for same.

You can check this SO answer written by Val for NativeSearch query builder.

There is currently a pull request being worked on that will allow to add source includes and source excludes to repository methods that are annotated with the @Query annotation, so this will be available in the next version.

Besides that, it is possible to set the source filter values to any provided implementation of the Query interface ( StringQuery , CriteriaQuery , NativeSearchQuery ). You'd need to create a repository fragment (see https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#repositories.custom-implementations ) to add a function that builds and uses one of these queries if you wish to integrate it in a repository.

The entity you use to read the data would need to have a property that matches the returned values like

@Document(indexName="populationstreamassignment")
public class Returned {
  @Id
  private String id;
  @Field(type= FieldType.text)
  private String memberId
  // getter and setter
}

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