创建springboot项目配置pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.3.0</version>
</dependency>
配置application.yml
testelasticsearch:
elasticsearch:
hostlist: 192.168.247.130:9200 #多个结点用逗号分隔
向spring容器中注入RestHighLevelClient
@Configuration
public class ElasticsearchConfig {
@Value("${testelasticsearch.elasticsearch.hostlist}")
private String hostlist;
@Bean
public RestHighLevelClient restHighLevelClient() {
//获得配置的ip:port的数组
String[] split = hostlist.split(",");
HttpHost[] httpHostArray = new HttpHost[split.length];
for (int i = 0; i < split.length; i++) {
String item = split[i];
//获得ip和端口
String[] ipAndPort = item.split(":");
httpHostArray[i] = new HttpHost(ipAndPort[0],Integer.parseInt(ipAndPort[1]), "http");
}
return new RestHighLevelClient(RestClient.builder(httpHostArray));
}
}
创建测试类并执行
创建索引
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestElasticsearchClient {
@Autowired
RestHighLevelClient client;
@Test
public void testCreateIndex() throws IOException {
//创建索引的请求对象
CreateIndexRequest createIndexRequest = new CreateIndexRequest("elasticsearch_test");
//设置分片和副本的参数
createIndexRequest.settings(Settings.builder()
.put("number_of_shards", "1")
.put("number_of_replicas", "0"));
// 在kibana中创建索引库的dsl写法
// PUT /elasticsearch_test
// {
// "settings": {},
// "mappings": {
// "properties": {
// "description": {
// "type": "text",
// "analyzer": "ik_max_word"
// },
// "name": {
// "type": "keyword"
// },
// "pic": {
// "type": "text",
// "index": false
// },
// "studymodel": {
// "type": "keyword"
// }
// }
// }
// }
// 创建mapping映射
XContentBuilder builder = XContentFactory.jsonBuilder()
//startObject是大括号的{,endObject是大括号的}
.startObject()
.field("properties")
.startObject()
.field("studymodel").
startObject().
field("index","true").
field("type", "keyword").
endObject()
.field("name").
startObject().
field("index","true").
field("type", "text").
endObject()
.field("description").
startObject().
field("index","true").
field("type", "text").
field("analyzer", "ik_max_word").
endObject()
.field("pic").
startObject().
field("index","false").
field("type", "text").
endObject()
.endObject()
.endObject();
createIndexRequest.mapping("doc", builder);
//操作索引的客户端
IndicesClient indices = client.indices();
//执行创建索引库
CreateIndexResponse createIndexResponse = indices.create(createIndexRequest,RequestOptions.DEFAULT);
//得到响应
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println(acknowledged);
}
}
在kibana查看索引库
删除索引
创建删除索引的测试方法
@Test
public void testDeleteIndex() throws IOException {
//创建删除索引的请求对象
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("elasticsearch_test");
//操作索引的客户端
IndicesClient indices = client.indices();
//执行删除索引
AcknowledgedResponse delete = indices.delete(deleteIndexRequest,RequestOptions.DEFAULT);
//得到响应
boolean acknowledged = delete.isAcknowledged();
System.out.println(acknowledged);
}
在kibana查询
插入文档
@Test
public void testAddDoc() throws IOException {
//创建索引请求对象
IndexRequest indexRequest = new IndexRequest("elasticsearch_test");
//绑定id
indexRequest.id("1");
//文档内容 准备json数据
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("name", "es搜索");
jsonMap.put("description", "啊啊啊啊测试一下这个插入");
jsonMap.put("studymodel", "201001");
//插入小数类型
jsonMap.put("price", 8.8f);
indexRequest.source(jsonMap);
//通过client进行http的请求
IndexResponse indexResponse = client.index(indexRequest,RequestOptions.DEFAULT);
DocWriteResponse.Result result = indexResponse.getResult();
System.out.println(result);
}
查看一下
用id查询文档
@Test
public void testGetDoc() throws IOException {
//查询请求对象
GetRequest getRequest = new GetRequest("elasticsearch_test","1");
GetResponse getResponse = client.get(getRequest,RequestOptions.DEFAULT);
//得到文档的内容
Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
System.out.println(sourceAsMap);
}
查询全部
@Test
public void testSearch() throws IOException{ //搜索请求对象
SearchRequest searchRequest = new SearchRequest("elasticsearch_test");
//搜索源构建对象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//搜索全部
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//termQuery
//searchSourceBuilder.query(QueryBuilders.termQuery("name","es"));
// 设置源字段过虑,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括哪些字段
searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","timestamp"},new String[]{});
//向搜索请求对象中设置搜索源
searchRequest.source(searchSourceBuilder); //执行搜索,向ES发起http请求
SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);
//搜索结果
SearchHits hits = searchResponse.getHits();
//匹配到的总记录数
TotalHits totalHits = hits.getTotalHits();
//通过hits得到文档
SearchHit[] searchHits = hits.getHits();
for(SearchHit hit:searchHits){
//文档的主键
String id = hit.getId();
//源文档内容
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
String name = (String) sourceAsMap.get("name");
//由于前边设置了源文档字段过虑,这里description是null
String description = (String) sourceAsMap.get("description");
String studymodel = (String) sourceAsMap.get("studymodel");
Double price = (Double) sourceAsMap.get("price");
System.out.println(name);
System.out.println(studymodel);
System.out.println(description);
System.out.println(price);
}
}
查看结果
termQuery查询
//把上面的
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//根据查询条件替换
searchSourceBuilder.query(QueryBuilders.termQuery("name","es"));
分页排序
设置起始页,size和排序方式
searchSourceBuilder.from(from);
searchSourceBuilder.size(size);
searchSourceBuilder.query(QueryBuilders.termQuery(“name”,“spring”));
@Test
public void testSearchByPage() throws IOException {
//搜索请求对象
SearchRequest searchRequest = new SearchRequest("elasticsearch_test");
//搜索源构建对象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//页码
int page = 1;
//每页记录数
int size = 2;
//计算出记录起始下标
int from = (page - 1) * size;
//起始记录下标,从0开始
searchSourceBuilder.from(from);
// 每页显示的记录数
searchSourceBuilder.size(size);
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//设置源字段过虑,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括哪些字段
searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "price", "timestamp"}, new String[]{});
//向搜索请求对象中设置搜索源
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); //搜索结果
SearchHits hits = searchResponse.getHits();
//匹配到的总记录数
TotalHits totalHits = hits.getTotalHits();
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
//文档的主键
String id = hit.getId();
//源文档内容
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
String name = (String) sourceAsMap.get("name");
//由于前边设置了源文档字段过虑,这时description是取不到的
String description = (String) sourceAsMap.get("description");
//学习模式
String studymodel = (String) sourceAsMap.get("studymodel");
//价格
Double price = (Double) sourceAsMap.get("price");
System.out.println(name);
System.out.println(studymodel);
System.out.println(description);
System.out.println(price);
}
}