在ElasticSearch中将SearchHit转换为Java对象

时间:2017-06-08 06:33:15

标签: java json elasticsearch

我正在尝试从ES查询中检索数据,我很困惑如何将每个检索到的数据转换为Java对象。 到目前为止,我可以使用Gson以JSON格式获取每个命中,但我认为从Hit转换为JSON然后转换为Java Object是没用的。

我目前的代码是:

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
    Settings settings = Settings.builder()
            .put("cluster.name", "elasticsearch")
            .put("path.home", "/Users/user/Apps/elasticsearch-5.4.1")
            .build();

    QueryBuilder qb = termQuery("price", 12);
    SearchResponse response = client.prepareSearch("kal").setTypes("products")
            .setSearchType(SearchType.DEFAULT)
            .setQuery(qb)
            .get();

    SearchHit[] results = response.getHits().getHits();
    for (SearchHit hit : results) {
        String sourceAsString = hit.getSourceAsString();
        Map<String, SearchHitField> responseFields = hit.getFields();
        if (sourceAsString != null) {
            Gson gson = new GsonBuilder().setDateFormat(sourceAsString)
                    .create();
        }
    }

3 个答案:

答案 0 :(得分:2)

一行

YourObject yourObject = new com.fasterxml.jackson.databind.ObjectMapper().convertValue(searchHit.getSourceAsMap(), YourObjectClass.class);

答案 1 :(得分:1)

我实施了这个解决方案,但我不确定这是否是正确的方法。

SearchHit[] results = response.getHits().getHits();
    for (SearchHit hit : results) {
        String sourceAsString = hit.getSourceAsString();
        Map<String, SearchHitField> responseFields = hit.getFields();
        SearchHitField field = responseFields.get("product_id");
        Map map = hit.getSource();
        System.out.println(map.toString());
    }

答案 2 :(得分:1)

    I am working with Elasticsearch version 7.4.2

    SearchHit[] searchHit = response.getHits().getHits();
            for (SearchHit hit : searchHit) {
                String jsonString=hit.getSourceAsString();
                TempClass tmpCl=(TempClass )JSONToObject.parser(jsonString, TempClass .class);
                System.out.println(tmpCl.toString());
            }


    // JSONToObject class
    private static Object dc;
    public static Object parser(String file, Class<?> cls) {
        try {
                Gson gson = new Gson();
                dc = gson.fromJson(file, cls);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return dc;
    }