gpt4 book ai didi

java - java中如何清除ClassCastException?

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

public List<LogLineEntry> query(){

List<LogLineEntry> timeRange = new ArrayList<LogLineEntry>();
Settings settings = Settings.settingsBuilder().put("cluster.name", "elasticsearch").build();
Client client = TransportClient.builder().settings(settings).build().addTransportAddress((TransportAddress) new InetSocketTransportAddress(new InetSocketAddress("127.0.0.1", 9300)));

SearchResponse sResponse = null;
QueryBuilder qb = QueryBuilders.rangeQuery("lineNumber").from(100).to(200);

while(sResponse== null|| sResponse.getHits().hits().length != 0){
int scrollSize=200, i=0;
sResponse = client.prepareSearch("jsonlogpage")
.setTypes("jsonlog")
.setQuery(QueryBuilders.matchAllQuery())
.setSize(scrollSize)
.setFrom(i * scrollSize)
.execute()
.actionGet();

for(SearchHit hit : sResponse.getHits()){
timeRange.add(hit); //add() shows error
}
i++;
}
return timeRange;

}

我正在使用搜索响应。我在 add() 中遇到错误。

错误:

Exception in thread "main" java.lang.ClassCastException: org.elasticsearch.search.internal.InternalSearchHit cannot be cast to com.example.elasticsearch.LogLineEntry

LogLineEntry是一个pojo类。我的列表是为LogLineEntry创建的,hit变量属于searchHit。所以我无法将 searchHit 变量添加到列表中。我该如何解决这个问题?

最佳答案

您需要将每个 SearchHit 转换为 LogLineEntry 实例。您不能仅将 SearchHit 实例添加到声明为包含 LogLineEntry 实例的 List 中。

因此,在 for 循环中,您需要创建一个 LogLineEntry 的新实例,并用在每个 SearchHit 实例中找到的字段填充它。

        for(SearchHit hit : sResponse.getHits()){
LogLineEntry entry = new LogLineEntry();
// populate your new instance
entry.setXyz(hit.getXyz());
// do this for each field

// add the instance to the list
timeRange.add(entry);
}

关于java - java中如何清除ClassCastException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39341306/

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