【问题标题】:How we add elastic search result(searchResponse) keys and value in a list where key is not duplicate我们如何在键不重复的列表中添加弹性搜索结果(searchResponse)键和值
【发布时间】:2015-07-30 18:59:09
【问题描述】:

我们如何在不希望列表中有重复键的列表中添加弹性搜索结果(searchResponse)键和值?因为我们想从我们的函数中返回一个列表。

      for (int i = 0; i < hits.totalHits(); i++) {      
                responseFields = (Map<String, Object>) hits.getAt(i).getSource();
                Student st=new Student();       
             Iterator it = responseFields.entrySet().iterator();
                 while (it.hasNext()) {
                     Map.Entry pair = (Map.Entry)it.next();
//use list here
                System.out.println(pair.getKey() + " = " + pair.getValue()+);
}}

在这种情况下,每次我们为每个 for 循环迭代获取重复键时。根据要求,我应该将结果保存在带有单个键的列表中。这可以在表表示中制作标题。

【问题讨论】:

  • 你用的是REST服务还是elastic的java api?
  • 您能否详细说明您的要求和实际响应格式?重复键的不同值应该怎么办?

标签: java elasticsearch


【解决方案1】:

一套几乎就是你想要的。这是一个特殊的列表,不允许重复(这是一个严重的过度简化)。

      Set uniqueValues = new HashSet<Entry>();
      for (int i = 0; i < hits.totalHits(); i++) {      
                responseFields = (Map<String, Object>) hits.getAt(i).getSource();
                Student st=new Student();       
             Iterator it = responseFields.entrySet().iterator();
                 while (it.hasNext()) {
                     Map.Entry pair = (Map.Entry)it.next();
                    uniqueValues.add(pair);
//use list here

}}

这应该可行,但前提是键和值对都必须是唯一的。

编辑:我刚刚看到如果你得到重复,你需要做一些事情。为此,您可以使用 uniqueValues.contains() 方法。它会告诉你它是否已经在集合中。所以:

if(!uniqueValues.contains(pair))
     uniqueValues.add(pair)
else addToTableOrSomething

如果您只希望键是唯一的,您可以使用 Map。它允许您只在密钥上执行 cointains()。

      Map uniqueValues = new HashMap<Something, Somthing>();
      for (int i = 0; i < hits.totalHits(); i++) {      
                responseFields = (Map<String, Object>) hits.getAt(i).getSource();
                Student st=new Student();       
             Iterator it = responseFields.entrySet().iterator();
                 while (it.hasNext()) {
                     Map.Entry pair = (Map.Entry)it.next();
                    if(!uniqueeValues.contains(pair.getKey())
                       uniqueValues.put(pair.getKey(), pair.getValue());
                    else doSomthingElse

//use list here

}}

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 2015-02-18
    • 2019-04-23
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多