kg_sYy
kg_sYy

Reputation: 1215

ElasticSearch 5.0 Java get specific fields

In ElasticSearch 2.X when I wanted to query for specific fields from a specific type in the Java API, I could do something like this:

  public List<String> getNames(String index, String type) {
    List<String> names = new ArrayList<>();
    SearchResponse scrollResp = client.prepareSearch()
        .setIndices(index)
        .setTypes(type)
        .addFields("my_name")
        .setQuery(QueryBuilders.matchAllQuery())
        .setSize(10).execute().actionGet();
    for (SearchHit hit : scrollResp.getHits().getHits()) {
      Map<String, SearchHitField> fields = hit.getFields();
      String name = fields.get("my_name").value();
      names.add(name);
    }
    return names;
  }

However, in ES 5.0, the "addFields" method is gone. There is something called "addStoredField". However, this does not seem to work if you have not explicitly marked your fields in the mapping as stored. Rather "hit.getFields()" for the code above simply returns an empty set of fields (fields.size() == 0).

How do I get the same functionality for 5.X as for 2.X? That is, get specific fields from the results, without explicitly storing them..?

I am using the PreBuiltTransportClient as the client here.

Upvotes: 1

Views: 1807

Answers (1)

Kulasangar
Kulasangar

Reputation: 9464

What if you're using the .setFetchSource method in order to define the fields which you're using:

SearchResponse scrollResp = client.prepareSearch()
        .setIndices(index)
        .setTypes(type)
        .setSearchType(SearchType.QUERY_AND_FETCH)
        .setFetchSource(new String[]{"my_name"}, null) <--- your specific field
        .setQuery(QueryBuilders.matchAllQuery())
        .setSize(10).execute().actionGet();

You could have a look over this SO as well.

Upvotes: 2

Related Questions