本文使用的是ElasticSearch7.17.3
对于索引的创建推荐使用Kibana工作台进行操作,本文主要讲解对文档的搜索,跟多操作可以看这篇博客https://blog.csdn.net/b___w/article/details/123924063
以下是在Kibana创建实验所需数据
PUT blog
{
"mappings": {
"properties": {
"id":{
"type":"long"
},
"title": {
"type": "text"
},
"content": {
"type": "text"
},
"author":{
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"category":{
"type": "keyword"
},
"createTime": {
"type": "date",
"format":"yyyy-MM-dd HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd HH:mm:ss||epoch_millis"
},
"updateTime": {
"type": "date",
"format":"yyyy-MM-dd HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd HH:mm:ss||epoch_millis"
},
"status":{
"type":"integer"
},
"serialNum": {
"type": "keyword"
}
}
}
}
POST _bulk
{"index":{"_index":"blog","_id":1}}
{"blogId":1,"title":"Spring Data ElasticSearch学习教程1","content":"这是批量添加的文档1","author":"Iron Man","category":"ElasticSearch","status":1,"serialNum":"1","createTime":"2021-10-10 11:52:01.249","updateTime":null}
{"index":{"_index":"blog","_id":2}}
{"blogId":2,"title":"Spring Data ElasticSearch学习教程2","content":"这是批量添加的文档2","author":"Iron Man","category":"ElasticSearch","status":1,"serialNum":"2","createTime":"2021-10-10 11:52:02.249","updateTime":null}
{"index":{"_index":"blog","_id":3}}
{"blogId":3,"title":"Spring Data ElasticSearch学习教程3","content":"这是批量添加的文档3","author":"Captain America","category":"ElasticSearch","status":1,"serialNum":"3","createTime":"2021-10-10 11:52:03.249","updateTime":null}
{"index":{"_index":"blog","_id":4}}
{"blogId":4,"title":"Spring Data ElasticSearch学习教程4","content":"这是批量添加的文档4","author":"Captain America","category":"ElasticSearch","status":1,"serialNum":"4","createTime":"2021-10-10 11:52:04.249","updateTime":null}
{"index":{"_index":"blog","_id":5}}
{"blogId":5,"title":"Spring Data ElasticSearch学习教程5","content":"这是批量添加的文档5","author":"Spider Man","category":"ElasticSearch","status":1,"serialNum":"5","createTime":"2021-10-10 11:52:05.249","updateTime":null}
{"index":{"_index":"blog","_id":6}}
{"blogId":6,"title":"Java学习教程6","content":"这是批量添加的文档6","author":"Spider Man","category":"ElasticSearch","status":1,"serialNum":"6","createTime":"2021-10-10 11:52:06.249","updateTime":null}
{"index":{"_index":"blog","_id":7}}
{"blogId":7,"title":"Java学习教程7","content":"这是批量添加的文档7","author":"Iron Man","category":"ElasticSearch","status":1,"serialNum":"7","createTime":"2021-10-10 11:52:07.249","updateTime":null}
{"index":{"_index":"blog","_id":8}}
{"blogId":8,"title":"Java学习教程8","content":"这是批量添加的文档8","author":"Iron Man","category":"ElasticSearch","status":1,"serialNum":"8","createTime":"2021-10-10 11:52:08.249","updateTime":null}
{"index":{"_index":"blog","_id":9}}
{"blogId":9,"title":"Java学习教程9","content":"这是批量添加的文档9","author":"Captain America","category":"ElasticSearch","status":1,"serialNum":"9","createTime":"2021-10-10 11:52:09.249","updateTime":null}
{"index":{"_index":"blog","_id":10}}
{"blogId":10,"title":"Java学习教程10","content":"这是批量添加的文档10","author":"God Of Thunder","category":"ElasticSearch","status":1,"serialNum":"10","createTime":"2021-10-10 11:52:10.249","updateTime":null}
pom.xml
org.projectlombok lombok co.elastic.clients elasticsearch-java 7.17.3 com.fasterxml.jackson.core jackson-databind 2.13.3 jakarta.json jakarta.json-api 2.0.1
application.yml
elasticsearch: # 集群可以用逗号隔开如127.0.0.1:9200,127.0.0.2:9200 uris: 你的IP:9200 username: elastic password: changeme
配置类
@Configuration
public class ElasticsearchConfig {
@Value("${elasticsearch.uris}")
private String nodes;
@Value("${elasticsearch.username}")
private String username;
@Value("${elasticsearch.password}")
private String password;
@Bean
public ElasticsearchClient client() {
// 集群时拆分ip
HttpHost[] httpHosts = Arrays.stream(nodes.split(",")).map(x -> {
String[] hostInfo = x.split(":");
return new HttpHost(hostInfo[0], Integer.parseInt(hostInfo[1]));
}).toArray(HttpHost[]::new);
// 账号和密码认证
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
// Create the low-level client
RestClient restClient = RestClient.builder(
httpHosts).setHttpClientConfigCallback(httpClientBuilder ->
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
).build();
// Create the transport with a Jackson mapper
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
// And create the API client
// 注意ElasticsearchClient不要导入接口那个包
return new ElasticsearchClient(transport);
}
}
能多创建低级客户端的方法可以看一下,感觉应该差不多,暂时没有尝试过ElasticSearch 应用开发(七)Java Low Level Rest Client——Java API - JavaShuo
实体类
//Setting是创建分片和副本,新版默认都是1,可以不写。
@Data
@Setting(shards = 1, replicas = 1)
@Document(indexName = "blog")
public class Blog {
//此项作为id,不会写到_source里边。
@Id
private Long blogId;
@Field(type = FieldType.Text)
private String title;
@Field(type = FieldType.Text)
private String content;
@Field(type = FieldType.Text)
private String author;
//博客所属分类。
@Field(type = FieldType.Keyword)
private String category;
//0: 未发布(草稿) 1:已发布 2:已删除
@Field(type = FieldType.Integer)
private int status;
//序列号,用于给外部展示的id
@Field(type = FieldType.Keyword)
private String serialNum;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
@Field(type= FieldType.Date, format= {}, pattern="yyyy-MM-dd HH:mm:ss.SSS")
private Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
@Field(type=FieldType.Date, format= {}, pattern="yyyy-MM-dd HH:mm:ss.SSS")
private Date updateTime;
}
使用
@RestController
@RequestMapping("clientQuery")
public class ElasticsearchController {
@Autowired
ElasticsearchClient client;
@GetMapping("simple")
public void simple() throws IOException {
// 查询索引
GetResponse getResponse = client.get(e -> e.index("blog").id("1"), Blog.class);
System.out.println("getResponse.source().toString() = " + getResponse.source().toString());
}
@GetMapping("simple2")
public List simple2(String title, String content) throws IOException {
SearchResponse response = client.search(s -> s
.index("blog")
.query(q -> q
.bool(b -> {
//多条件查询
if (StringUtils.isNotBlank(title)) {
b.must( t-> t.matchPhrase(v -> v.field("title").query(title)));
}
if (StringUtils.isNotBlank(content)) {
b.must( t-> t.matchPhrase(v -> v.field("content").query(content)));
}
//范围查询
b.filter(f->f.range(r->r.field("blogId").gte(JsonData.of(5)).lt(JsonData.of(10))));
return b;
})
)
//排序
.sort(sort -> sort.field(f->f.field("createTime").order(Desc))),
Blog.class
);
List> hits = response.hits().hits();
List blogs = new ArrayList<>();
for (Hit hit: hits) {
blogs.add(hit.source());
}
return blogs;
}
}



