ElasticSearch做分布式的搜索引擎练习
需要导入的pom文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--引入es的坐标-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.4.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.4.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
</dependencies>
application.yaml文件
elasticsearch:
host: 127.0.0.1
port: 9200
启动类创建
package com.atguigu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ElasticsearchDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ElasticsearchDemoApplication.class, args);
}
}
创建一个客户端的类
import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticSearchConfig {
private Integer port;
private String host;
//注册一个客户端
@Bean
public RestHighLevelClient client(){
return new RestHighLevelClient(RestClient.builder(new HttpHost(host,port,"http")));
}
}
创建一个JavaBean对象
@Data
public class Person implements Serializable {
private Integer age;
private String name;
private String address;
// private Integer id;
}
创建一个测试类进行增删改查索引,文档,以及进行批量添加删除等操作
@SpringBootTest
@RunWith(SpringRunner.class)
public class ElasticSearchTest {
//导入客户端
@Autowired
private RestHighLevelClient client;
/**
* 创建索引
* @throws Exception
*/
@Test
public void test1()throws Exception{
//获取操作索引的对象
IndicesClient indices = client.indices();
//创建索引的请求
CreateIndexRequest request = new CreateIndexRequest("abc");
//利用索引的对象创建索引
CreateIndexResponse createIndexResponse = indices.create(request, RequestOptions.DEFAULT);
//创建完成返回结果
System.out.println(createIndexResponse.isAcknowledged());
}
/**
* 添加索引与映射
*/
@Test
public void test2()throws Exception{
//获取索引创建对象
IndicesClient indices = client.indices();
//创建请求
CreateIndexRequest indexRequest = new CreateIndexRequest("aaa");
//将映射放进请求
String mapping="{\n" +
" \"properties\" : {\n" +
" \"address\" : {\n" +
" \"type\" : \"text\",\n" +
" \"analyzer\" : \"ik_max_word\"\n" +
" },\n" +
" \"age\" : {\n" +
" \"type\" : \"long\"\n" +
" },\n" +
" \"name\" : {\n" +
" \"type\" : \"keyword\"\n" +
" }\n" +
" }\n" +
" }";
indexRequest.mapping(mapping, XContentType.JSON);
//创建索引以及映射
CreateIndexResponse createIndexResponse = indices.create(indexRequest, RequestOptions.DEFAULT);
System.out.println(createIndexResponse.isAcknowledged());
}
/**
* 查询索引
*/
@Test
public void test3()throws Exception{
//创建索引对象
IndicesClient indices = client.indices();
//创建查询索引请求
GetIndexRequest getIndexRequest = new GetIndexRequest("aaa");
//发送请求
GetIndexResponse indexResponse = indices.get(getIndexRequest, RequestOptions.DEFAULT);
//遍历请求的参数
Map<String, MappingMetaData> mappings = indexResponse.getMappings();
Set<Map.Entry<String, MappingMetaData>> entries = mappings.entrySet();
for (Map.Entry<String, MappingMetaData> entry : entries) {
System.out.println(entry.getKey());
System.out.println(mappings.get(entry.getKey()).getSourceAsMap());
}
}
/**
* 删除索引
*/
@Test
public void test4()throws Exception{
//创建操作索引的对象
IndicesClient indices = client.indices();
//创建删除索引请求
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("abc");
//发送请求进行删除
AcknowledgedResponse delete = indices.delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
/**
* 判断索引是否存在
*/
@Test
public void test5()throws Exception{
IndicesClient indices = client.indices();
GetIndexRequest getIndexRequest = new GetIndexRequest("abc");
boolean exists = indices.exists(getIndexRequest, RequestOptions.DEFAULT);
System.out.println("exists = " + exists);
}
/**
* 添加文档数据
* @throws Exception
*/
@Test
public void test6()throws Exception{
//创建一个map集合存数据
Map map = new HashMap();
map.put("name","小红");
map.put("age",55);
map.put("address","佛山");
//获取文档对象并添加数据
IndexRequest indexRequest = new IndexRequest("aaa").id("1").source(map);
//利用客户端发送请求
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(indexResponse.getId());
}
/**
* 利用JavaBean发送请求创建文档/修改文档
*/
@Test
public void test7()throws Exception{
Person person = new Person();
person.setAddress("北京");
person.setAge(56);
person.setName("小亮");
// person.setId(2);
//将对象转成json格式
String s = JSON.toJSONString(person);
// 创建文档对象并添加数据
IndexRequest indexRequest = new IndexRequest("aaa").id("3").source(s,XContentType.JSON);
//发送请求
IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(index.getId());
}
/**
* 利用id进行查询
* @throws Exception
*/
@Test
public void test8()throws Exception{
//创建查询id请求
GetRequest getRequest = new GetRequest("aaa", "2");
//发送请求
GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
String sourceAsString = response.getSourceAsString();
System.out.println( sourceAsString);
}
/**
* 删除文档
* @throws Exception
*/
@Test
public void test9()throws Exception{
//创建删除请求
DeleteRequest deleteRequest = new DeleteRequest("aaa", "2");
DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(response.getId());
}
/**
* 批量操作
* @throws Exception
*/
@Test
public void test10()throws Exception{
//创建绑定对象请求
BulkRequest bulkRequest = new BulkRequest();
//创建增删改的请求
Person person = new Person();
person.setName("小米");
person.setAge(33);
person.setAddress("天津");
String string1 = JSON.toJSONString(person);
IndexRequest put = new IndexRequest("aaa").id("2").source(string1,XContentType.JSON);
bulkRequest.add(put);
DeleteRequest deleteRequest = new DeleteRequest("aaa", "1");
bulkRequest.add(deleteRequest);
/*
Person person1 = new Person();
person.setName("小黄");
String string = JSON.toJSONString(person1);*/
Map map=new HashMap();
map.put("name","小黄");
UpdateRequest updateRequest = new UpdateRequest("aaa", "3").doc(map);
bulkRequest.add(updateRequest);
BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulk.status());
}
}