这是我发送 list 的代码:
for (int i = 0; i < list.size(); i++) {
request.add(new IndexRequest("myindex", "doc").source(list,XContentType.JSON));
count++;
}
我也尝试将列表转换为 map 形式,但它正在创建索引并多次击中,但未推送任何数据:
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"
}]
最佳答案
假设索引创建成功,这就是您可以发布列表中存在的数据的方式。
所以,我创建了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
}
}
关于java - 如何使用BulkRequest将ArrayList发送到ElasticSearch中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61821452/