gpt4 book ai didi

java - 在ElasticSearch中将SearchHit转换为Java对象

转载 作者:行者123 更新时间:2023-12-02 22:58:03 34 4
gpt4 key购买 nike

我正在尝试从ES查询中检索数据,但对如何将检索到的数据的每个匹配转换为Java Object感到困惑。
到目前为止,我可以使用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();
}
}

最佳答案

    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;
}

关于java - 在ElasticSearch中将SearchHit转换为Java对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44428271/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com