TL;DR
如果您从班级中删除 @Document 注释,Spring-Data-Elasticseach 将不再工作。
说明:
如果你从你的类中删除@Document,在读取或写入(确定索引名称、类型和ID 时)时,几个elasticsearch 操作将失败,因为ElasticsearchTemplate.getPersistentEntityFor(Class clazz) 严重依赖此注释。
解决方案
我已经成功地使用一个带有虚拟注释@Document(indexName = "dummy", createIndex = false) 的带注释类成功地使用不同的索引读取/写入,并使用 elasticsearchTemplate 为所有读取/写入操作显式设置索引名称。
证明
写作与
ElasticEntity foo = new ElasticEntity();
foo.setAid("foo-a-id");
foo.setEntityId("foo-entity-id");
foo.setUserName("foo-user-name");
foo.setUserId("foo-user-id");
IndexQuery fooIdxQuery = new IndexQueryBuilder()
.withIndexName("idx-foo")
.withObject(foo)
.build();
String fooId = template.index(fooIdxQuery);
和
ElasticEntity bar = new ElasticEntity();
bar.setAid("bar-a-id");
bar.setEntityId("bar-entity-id");
bar.setUserName("bar-user-name");
bar.setUserId("bar-user-id");
IndexQuery barIdxQuery = new IndexQueryBuilder()
.withIndexName("idx-bar")
.withObject(bar)
.build();
String barId = template.index(barIdxQuery);
应该将对象存储在不同的索引中。
使用curl http://localhost:9200/idx-*/_search?pretty 进行双重检查:
{
"took" : 3,
"timed_out" : false,
"_shards" : {
"total" : 10,
"successful" : 10,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 2,
"max_score" : 1.0,
"hits" : [
{
"_index" : "idx-bar",
"_type" : "elasticentity",
"_id" : "bar-a-id",
"_score" : 1.0,
"_source" : {
"aid" : "bar-a-id",
"userId" : "bar-user-id",
"entityId" : "bar-entity-id",
"userName" : "bar-user-name"
}
},
{
"_index" : "idx-foo",
"_type" : "elasticentity",
"_id" : "foo-a-id",
"_score" : 1.0,
"_source" : {
"aid" : "foo-a-id",
"userId" : "foo-user-id",
"entityId" : "foo-entity-id",
"userName" : "foo-user-name"
}
}
]
}
}
如您所见,响应中的索引名称和 _id 是正确的。
阅读也可以使用以下代码(您需要根据需要更改查询并将索引设置为当前客户端)
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery())
.withIndices("idx-foo", "idx-bar")
.build();
List<ElasticEntity> elasticEntities = template.queryForList(searchQuery, ElasticEntity.class);
logger.trace(elasticEntities.toString());
映射也起作用,因为 logger 在结果中产生完全填充的类:
[ElasticEntity(aid=bar-a-id, userId=bar-user-id, entityId=bar-entity-id, userName=bar-user-name), ElasticEntity(aid=foo-a-id, userId=foo-user-id, entityId=foo-entity-id, userName=foo-user-name)]
希望这有帮助!