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()中遇到错误。

错误:



LogLineEntry是一个pojo类。我的列表是为LogLineEntry创建的,命中变量属于searchHit。所以我不能将searchHit变量添加到List中。我该如何解决?

最佳答案

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

因此,在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/

10-11 09:07