公司在用 es 版本
7.14.2
jar 包引入
这里高于公司在用版本,从使用情况来看,基本上是有兼容的
compile("co.elastic.clients:elasticsearch-java:7.17.2")
// 项目存在低版本的 httpclient, 会导致 es 请求出现问题,所以引入了最新版本的 httpclient
compile("org.apache.httpcomponents:httpclient:4.5.13")
elasticSearch 官方链接
https://www.elastic.co/guide/en/elasticsearch/reference/7.17/index.html
配置
配置类
// ... 此处省略各种 import
@Configuration
@ConfigurationProperties(prefix = "demo.elasticsearch")
@RefreshScope
@RefreshBinder
public class EsConfig {
private Integer port;
private String host;
private String username;
private String password;
@ApiModelProperty("第三方信息索引")
private String oauthIndexName;
@ApiModelProperty("第三方信息索引别名")
private String oauthIndexAliasName;
@ApiModelProperty("基本信息索引")
private String accountIndexName;
@ApiModelProperty("基本信息索引别名")
private String accountIndexAliasName;
@Bean
public ElasticsearchClient getElasticSearchClient() {
// 线下,线上都是有配置了访问账号的
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
// Create the low-level client
RestClientBuilder builder = RestClient.
builder(new HttpHost(host, port))
.setHttpClientConfigCallback(httpClientBuilder ->
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
);
RestClient restClient = builder.build();
// Create the transport with a Jackson mapper
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
//这里只返回了 Java API Client
return new ElasticsearchClient(transport);
}
public EsConfig(Integer port, String host, String username, String password, String oauthIndexName, String oauthIndexAliasName, String accountIndexName, String accountIndexAliasName) {
this.port = port;
this.host = host;
this.username = username;
this.password = password;
this.oauthIndexName = oauthIndexName;
this.oauthIndexAliasName = oauthIndexAliasName;
this.accountIndexName = accountIndexName;
this.accountIndexAliasName = accountIndexAliasName;
}
public EsConfig() {
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getOauthIndexName() {
return oauthIndexName;
}
public void setOauthIndexName(String oauthIndexName) {
this.oauthIndexName = oauthIndexName;
}
public String getOauthIndexAliasName() {
return oauthIndexAliasName;
}
public void setOauthIndexAliasName(String oauthIndexAliasName) {
this.oauthIndexAliasName = oauthIndexAliasName;
}
public String getAccountIndexName() {
return accountIndexName;
}
public void setAccountIndexName(String accountIndexName) {
this.accountIndexName = accountIndexName;
}
public String getAccountIndexAliasName() {
return accountIndexAliasName;
}
public void setAccountIndexAliasName(String accountIndexAliasName) {
this.accountIndexAliasName = accountIndexAliasName;
}
}
配置文件
demo:
elasticsearch:
host: 127.0.0.1
port: 9200
username: "username"
password: "password"
oauth-index-name: "xxxx"
oauth-index-alias-name: "xxxx"
account-index-name: "yyyyy"
account-index-alias-name: "yyyyy"
如何使用
High Level Rest Client 废弃
这个类,官方已废弃, 推荐在代码中使用 Java API Client
,所以在elasticSearch 配置类中, 只通过 @Bean 注入Java API Client
如何使用 Java API Client
插入新文档
JAVA 语法示例
elasticsearchClient.index(i -> i
.index("indexName")
.id("文档id")
.document("文档内容, 实例化后的对象")
);
更新文档
更新文档有2种方式,一种是通过文档id, 另外一种则是根据查询结果更新
通过文档id 更新
JAVA 语法示例
Map<String, Object> updateMap = new HashMap<>();
updateMap.put("fieldName", "fieldValue")
elasticsearchClient.update(UpdateRequest.of(o -> o
.index("indexName")
.id("文档id")
.doc(updateMap)), IndexUserInfo.class); // 这里要指定实体的 class 对象
通过查询条件更新
JAVA 语法示例
UpdateByQueryRequest.Builder builder = new UpdateByQueryRequest.Builder();
// bool 是组合查询
// must 要求必须匹配
builder.query(q -> q.bool(b -> b
.must(TermQuery.of(o -> o.field("fieldName1").value("fieldValue1"))._toQuery())
.must(TermQuery.of(o -> o.field("fieldName2").value("fieldValue2"))._toQuery())
)
);
// 这里通过脚本的方式去更新
Script.Builder scriptBuilder = new Script.Builder();
// InlineScript
InlineScript.Builder inlineScriptBuilder = new InlineScript.Builder();
// 更新的内容, 根据自己需要替换成想要的操作
inlineScriptBuilder.source("ctx._source['is_deleted'] = 1");
// 接收 Inline 类型的脚步
scriptBuilder.inline(inlineScriptBuilder.build());
// 指定索引名
builder.index(esConfig.getOauthIndexName());
// scriptBuilder.build() 实例化 Script
builder.script(scriptBuilder.build());
try {
elasticsearchClient.updateByQuery(builder.build());
} catch (Exception exception) {
// ...
}
查询文档
简易条件查询
JAVA 语法示例
SearchResponse<IndexUserInfo> indexUserInfoResponse = elasticsearchClient.search(s -> s
.index("indexName")
.query(q -> q.match(t -> t.field("username").query("xxxxx")))
, IndexUserInfo.class);
Optional<Hit<IndexUserInfo>> first = indexUserInfoResponse.hits().hits().stream().findFirst();
return first.map(Hit::source).orElse(null);
查询文档总数
JAVA 语法示例
CountRequest.Builder builder = new CountRequest.Builder();
builder.index("indexName");
CountResponse count = elasticsearchClient.count(builder.build());
return count.count();
网友评论