1

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.

1 Answer 1

2

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.

1
  • what is the 'client.prepareSearch' where do I get it from? Aug 6, 2019 at 11:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.