0

I am working with Elasticcsearch 7.3. I want to fetch only two records of all the documents using JAVA Api from my index. I am using the following code but it returning the null object.

        RestHighLevelClient client;

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.fetchSource("recipe_ID,recipe_url", null);
        sourceBuilder.from(0);
        SearchRequest searchRequest = new SearchRequest("recipes");
        searchRequest.source(sourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchHit searchHit = searchResponse.getHits().getAt(0);

        String resultString = searchHit.getSourceAsString();

        return resultString;

I need to include only two fields recipe_ID and recipe_url in my result.

Lily
  • 605
  • 3
  • 15
  • 31

1 Answers1

1

You're on the right path, although source filtering requires you to specify your fields in an array like this:

    String[] includeFields = new String[] {"recipe_ID", "recipe_url"};
    sourceBuilder.fetchSource(includeFields, null);
Val
  • 207,596
  • 13
  • 358
  • 360