我尝试将弹性数据映射到列表。因为不推荐使用getSourceAsObjectList()方法,所以我制作了这样的代码。
class activityObj {
private String name;
private String oid;
public String getName()
{
return name;
}
public void setName( String name)
{
this.name = name;
}
public String getOid()
{
return oid;
}
public void setOid( String oid)
{
this.oid = oid;
}
}
List< Hit<activityObj, Void>> hits = result.getHits(activityObj.class);
List< activityObj> list = new ArrayList<activityObj>();
for (SearchResult.Hit<activityObj, Void> hit: hits) {
activityObj objectSource = hit.source; // null point error
list.add(objectSource);
logger.info( "hits : " + objectSource.getName());
}
它没有像我期望的那样工作并且看起来很乱(它使用两个列表值来映射结果)。我做错了吗?
答案 0 :(得分:2)
你有没有试过这样的事情:
List< activityObj> list = hits.stream().map(h -> h.source).collect(Collectors.toList());
答案 1 :(得分:2)
在我的情况下,我想获得从结果中每个文档的来源收集的用户ID列表。
class DocSource {
private Integer userId;
public Integer getUserId() {
return userId;
}
}
String query = "{\n"
+ " \"_source\": [\n"
+ " \"userId\"\n"
+ " ],\n"
+ " \"query\": {\n"
+ " <some query config here>"
+ " }\n"
+ " }\n"
+ "}";
Search search = new Search.Builder(query)
.addIndex("my-index")
.build();
SearchResult result = jestClient.execute(search);
List<SearchResult.Hit<DocSource, Void>> hits = result.getHits(DocSource.class);
List<Integer> listOfIds = hits.stream()
.map(h -> h.source.getUserId())
.collect(Collectors.toList());