ElasticsearchRestTemplate不能将多个文档保存到不同的索引



我有一个测试域类

public class TestDocument {
private final String id;
private final String strField;
private final Integer intField;
public TestDocument(final String id, final String strField, final Integer intField) {
this.id = id;
this.strField = strField;
this.intField = intField;
}

}

现在我用3个文档调用ElasticsearchRestTemplate.save方法,并希望保存到3个不同的索引中。

@Service
public class TestEsService {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
@PostConstruct
public void testSave() {
final TestDocument d1 = new TestDocument("id_1", "str1", 1);
final TestDocument d2 = new TestDocument("id_2", "str2", 2);
final TestDocument d3 = new TestDocument("id_3", "str3", 3);
this.save(List.of(d1, d2, d3));
}
public void save(final List<TestDocument> documents) {
final IndexCoordinates indexCoordinates = IndexCoordinates.of("index_1", "index_2", "index_3");

this.elasticsearchRestTemplate.save(documents, indexCoordinates);
}
}

执行以上代码后。我检查了本地的elasticsearch。curl -H 'Content-Type: application/json' 'http://localhost:9200/_cat/indices?pretty' -s

我在ES中只得到一个索引。yellow open index_1 17ppJ9vJRUGIVHYBKKxXog 1 1 3 0 5.5kb 5.5kb

,核对index_1指数数据:

curl 'http://localhost:9200/index_1/_search?pretty'
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "index_1",
"_type" : "_doc",
"_id" : "id_1",
"_score" : 1.0,
"_source" : {
"_class" : "com.test.entity.TestDocument",
"id" : "id_1",
"strField" : "str1",
"intField" : 1
}
},
{
"_index" : "index_1",
"_type" : "_doc",
"_id" : "id_2",
"_score" : 1.0,
"_source" : {
"_class" : "com.test.entity.TestDocument",
"id" : "id_2",
"strField" : "str2",
"intField" : 2
}
},
{
"_index" : "index_1",
"_type" : "_doc",
"_id" : "id_3",
"_score" : 1.0,
"_source" : {
"_class" : "com.test.entity.TestDocument",
"id" : "id_3",
"strField" : "str3",
"intField" : 3
}
}
]
}
}

进入代码后:

我在RequestFactory.bulkRequest中找到了一个线索:

queries.forEach(query -> {
if (query instanceof IndexQuery) {
bulkRequest.add(indexRequest((IndexQuery) query, index));
} else if (query instanceof UpdateQuery) {
bulkRequest.add(updateRequest((UpdateQuery) query, index));
}
});

实际上IndexRequest()通过index.getIndexName();方法获得索引名称:

public IndexRequest indexRequest(IndexQuery query, IndexCoordinates index) {
String indexName = index.getIndexName();
IndexRequest indexRequest;

其中IndexCoordinates.getIndexName()只返回第一个索引名。


public String getIndexName() {
return indexNames[0];
}

是bug吗?我应该报告spring-data-elasticsearch Github问题吗?

IndexCoordinates中的多个名称用于访问使用多个索引名称的Elasticsearch API,例如在多个索引中搜索数据,但不用于写访问。

如果你想把3个实体保存到3个索引,你需要3次调用不同的IndexCoordinates-每个都有一个索引名。

最新更新