[英]Specify indexName and type of index in elasticsearch in a properties file
我在我的应用程序中使用了 elasticsearch 和 spring。 对于每种索引类型,我都有一个文档映射。 使用@Document
注释,我指定了indexName
和索引type
。 例如: @Document(indexName = "myproject", type = "user")
。 但是为了编写单元测试,我想用不同的 indexName 创建索引。 因此,我希望从属性文件中读取 indexName。 在春天如何做到这一点?
您只需使用 SPeL 即可解决此问题。 它允许您设置 Spring 将在编译时解析的表达式。 因此允许在编译期间处理注释。
@Document(collection = "#{@environment.getProperty('index.access-log')}")
public class AccessLog{
...
}
在 Spring 5.x 之前:
请注意,SPeL 中没有@
。
@Document(collection = "#{environment.getProperty('index.access-log')}")
public class AccessLog{
...
}
此外,我发现 Spring 还支持更简单的表达式@Document(collection = "${index.access-log}")
但我对此产生了混合结果。
如上所述设置注释后,您可以使用
application.properties
index.access-log=index_access
或application.yaml
index :
access : index_access
只需使用单元测试中的 ElasticSearchTemplate 来创建具有不同名称的索引,然后使用“index”或“bulkIndex”方法将文档索引到您刚刚创建的新索引中。
esTemplate.createIndex(newIndexName, loadfromFromFile(settingsFileName));
esTemplate.putMapping(newIndexName, "user", loadfromFromFile(userMappingFileName));
List<IndexQuery> indexes = users.parallelStream().map(user -> {
IndexQuery index = new IndexQuery();
index.setIndexName(newIndexName);
index.setType("user");
index.setObject(user);
index.setId(String.valueOf(user.getId()));
return index;
}).collect(Collectors.toList());
esTemplate.bulkIndex(indexes);
//Load file from src/java/resources or /src/test/resources
public String loadfromFromFile(String fileName) throws IllegalStateException {
StringBuilder buffer = new StringBuilder(2048);
try {
InputStream is = getClass().getResourceAsStream(fileName);
LineNumberReader reader = new LineNumberReader(new InputStreamReader(is));
while (reader.ready()) {
buffer.append(reader.readLine());
buffer.append(' ');
}
} catch (Exception e) {
throw new IllegalStateException("couldn't load file " + fileName, e);
}
return buffer.toString();
}
这应该对我有用。 同样的场景。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.