【问题标题】:How to send an ArrayList into ElasticSearch using BulkRequest?如何使用 BulkRequest 将 ArrayList 发送到 ElasticSearch?
【发布时间】:2020-09-01 09:50:13
【问题描述】:

这是我发送列表的代码:

for (int i = 0; i < list.size(); i++) {
        request.add(new IndexRequest("myindex", "doc").source(list,XContentType.JSON));
        count++;
        }

我也尝试以地图的形式转换列表,但它正在创建索引并多次点击,但没有推送任何数据:

for (int i = 0; i < list.size(); i++) {
        JSONObject dataAsJson = new JSONObject(list);
        HashMap<String, Object> dataAsMap = new HashMap<String, Object>(dataAsJson.toMap()); 
        request.add(new IndexRequest("myindex", "doc").source(dataAsMap,XContentType.JSON));
        }

这是我要加载的示例数据:

           [{"Name" : "ABC",
          "Class" : "six",                                                    
          "Roll" : "330344953  ",
          "Team" : "XYX"
          },
           {"Name" : "AEBC",
          "Class" : "six",                                                    
          "Roll" : "3344953  ",
          "Team" : "XYZ"
          }]

【问题讨论】:

  • 您能否对您尝试索引的数据或列表的内容进行采样。
  • 我已经更新了相关数据
  • 这个 ObjectMapper 是 org.elasticsearch.index.mapper 的一个类吗?
  • 抱歉没有提及。它是Jackson import com.fasterxml.jackson.databind.ObjectMapper 的一个类;也会更新答案。
  • 非常感谢!它解决了我的问题。

标签: java json elasticsearch arraylist hashmap


【解决方案1】:

假设您的索引创建成功,这就是您可以发布列表中存在的数据的方式。

所以,我将list 创建为:

List<Test> list = new ArrayList<Test>();

Test first = new Test();
first.setName("ABC");
first.setClassname("six");
first.setRoll(1);
first.setTeam("XYZ");

Test sec = new Test();
sec.setName("ABCDE");
sec.setClassname("tenth");
sec.setRoll(2);
sec.setTeam("XYZ");

list.add(first);
list.add(sec);

Test 与您提到的对象结构相同:

class Test {

    private String name;
    private String classname;
    private int roll;
    private String team;
}

这是您可以使用此list 为您的文档编制索引的方法:

代码:

    import com.fasterxml.jackson.databind.ObjectMapper;


    class TestService {

       private ObjectMapper objectMapper;
       @Autowired
       public TestService(ObjectMapper objectMapper) {
         this.objectMapper = objectMapper;
       }

       public String createBulkDocument() {

          BulkRequest request = new BulkRequest();
          IndexRequest indexRequest;
          for(int index=0;index<list.size();index++) {
                Map<String, Object> documentMapper = objectMapper.convertValue(list.get(index), Map.class);
                indexRequest = new IndexRequest("myindex", "doc")
                        .source(documentMapper);
                request.add(indexRequest);
            }
         BulkResponse bulkresp=client.bulk(request, RequestOptions.DEFAULT); --> `client` is your elasticsearch rest level client
        return bulkresp.status().toString();     ---> This will return the status
 whether your documents got indexed or not
      }
  }

【讨论】:

    猜你喜欢
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 2021-07-09
    • 2019-05-07
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    相关资源
    最近更新 更多