Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ElasticSearch Java API to query and return single column instead of the whole json document

While searching using java api in elaticsearch, I would like to retrieve only one column. Currently when I query using the Java API it returns the whole record like this: [{_id=123-456-7890, name=Wonder Woman, gender=FEMALE}, {_id=777-990-7890, name=Cat Woman, gender=FEMALE}]

The record above correctly matches the search condition shown in th . As shown in the code below:

        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();


        SearchRequestBuilder srb = client.prepareSearch("heros")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
        MatchQueryBuilder mqb;

        mqb = QueryBuilders.matchQuery("name", "Woman");
        srb.setQuery(mqb);
        SearchResponse response = srb.execute().actionGet();
        long totalHitCount = response.getHits().getTotalHits();

        System.out.println(response.getHits().getTotalHits());

        for (SearchHit hit : response.getHits()) {          
            result.add(hit.getSource());
        }

        System.out.println(result);

I want only one column to be returned. If I search for name I just want the full names back in a list: "Wonder Woman", "Cat Woman" only not the whole json record for each of them. If you think I need to iterate over the result list of maps in java please propose an example of how to do that in this case.

like image 974
Horse Voice Avatar asked Dec 07 '25 03:12

Horse Voice


1 Answers

You can specify the fields to be returned from a search, per documentation. This can be set via SearchRequestBuilder.addFields(String... fields), ie:

    SearchRequestBuilder srb = client.prepareSearch("heros")
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .addFields("name");
like image 199
femtoRgon Avatar answered Dec 08 '25 16:12

femtoRgon