将elasticsearch内部命中结果Map到java中的类

ohtdti5x  于 2023-04-29  发布在  ElasticSearch
关注(0)|答案(1)|浏览(94)

我甚至不知道如何正确地表达这个问题,所以这是我最好的。
这是我从一个名为“attributes”的嵌套字段中获取innerhits的结果,我为一个索引(在过滤掉元数据之后):

"inner_hits" : {
 "attributes" : {
  "hits" : {
    "hits" : [
      {
         "_source" : {
         "name" : "Title",
         "value" : "title title"
         }
       },
       {
         "_source" : {
          "name" : "Author",
          "value" : "Test"
          }
        },
        {
          "_source" : {
          "name" : "Timestamp",
          "value" : "20.12.2022 11:06:03"
          }
         }
    ]
   }
  }
}

在其他查询中,我只是像这样返回整个文档,所以它是自动Map的。在这种情况下,属性只是自动Map到MyClass中的List<AttributeClass>属性:

MyClass doc = null;

SearchResponse<MyClass> search = client
               .search(
                  s -> s
                     .index(myIndex)
                     .query(some-query),
                  MyClass.class);

List<Hit<MyClass>> hits = search.hits().hits();
for(Hit<MyClass> hit: hits) {doc = hit.source();}

return doc;

然而,现在我试图用innerhits来“过滤”东西,结构有点不同。我不知道如何将内部hits列表“Map”回原始类,因为它是hits.hits.source之外的一个独立部分,并且再次拥有自己的源代码。我是不是应该用它来创建一个新的json?结果应该是一个可读的JSON。
附加信息:我用的是spring Boot 和ES 7。17.3

jmp7cifd

jmp7cifd1#

我对未来的自我和任何需要想法的人的解决方案。我不认为我走的是最好的方法,我愿意接受任何更有效的想法:
由于我的项目中有一些特殊的结构,我不得不将其打包在Map中,以保持对键值对的跟踪。我会避免所有不相关的事情

//imagine there's a SearchResponse called search here...
List<Hit<ClassForWholeResult>> hits = search.hits().hits();

for(Hit<ClassForWholeResult> hit: hits) {
  Pair<String, List<Hit<JsonData>>> firstPair = Pair
                  .of(firstPairKey, hit.innerHits().get(INNER_HIT_FIELD_NAME).hits().hits());
  
   //I had to insert my pairs into a map, I'm omitting it
}

//looping into the pairs that got inserted, pretend there's a loop for the map here
for(Pair<String, List<Hit<JsonData>>> pair: entryValue) {
   String pairKey = pair.getLeft();
   List<Hit<JsonData>> pairValue = pair.getRight();
   for(Hit<JsonData> innerhit: pairValue) {
       //I'm storing my results in a list
       storingList.add(innerhit.source().to(CORRESPONDING_CLASS.class));
}

相关问题