1. ElasticSearch
1.1 倒排索引
1.2 ElasticSearch和Mysql对比
1.3 RestClient操作
导入依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.15.0</version>
</dependency>
并设置
<elasticsearch.version>7.15.0</elasticsearch.version>
添加ElasticSearch配置
java
@Configuration
public class ElasticSearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client=new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1",9200,"http"))
);
return client;
}
}
索引的创建,判断是否存在,删除
java
CreateIndexRequest createIndexRequest=new CreateIndexRequest("test");
restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
//判断某个索引库是否存在
GetIndexRequest getIndexRequest=new GetIndexRequest("test");
boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
System.out.println(exists);
//删除某个索引库
DeleteIndexRequest deleteIndexRequest=new DeleteIndexRequest("test");
restHighLevelClient.indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);
添加文档
java
IndexRequest in = new IndexRequest("test").id("1").source("{\n" +
" \"username\":\"admin\",\n" +
" \"password\":\"admin\"\n" +
"}", XContentType.JSON);
restHighLevelClient.index(in,RequestOptions.DEFAULT);
查找文档
java
GetRequest getRequest=new GetRequest("test","1");
GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse.getSourceAsString());
更新文档
java
//全量更新,再次写入id一样的文档,就会删除旧文档,添加新文档
IndexRequest in = new IndexRequest("test").id("1").source("{\n" +
" \"username\":\"admin\",\n" +
" \"password\":\"helloworld\"\n" +
"}", XContentType.JSON);
restHighLevelClient.index(in,RequestOptions.DEFAULT);
UpdateRequest updateRequest=new UpdateRequest("test","1");
updateRequest.doc(
"password","hello"
);
restHighLevelClient.update(updateRequest,RequestOptions.DEFAULT);
删除文档
java
DeleteRequest deleteRequest=new DeleteRequest("test","1");
restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
批量导入文档
java
BulkRequest bulkRequest=new BulkRequest();
bulkRequest.add(new IndexRequest("test").id("2").source("{\n" +
" \"username\":\"hello\",\n" +
" \"password\":\"hello\"\n" +
"}",XContentType.JSON));
bulkRequest.add(new IndexRequest("test").id("3").source("{\n" +
" \"username\":\"world\",\n" +
" \"password\":\"world\"\n" +
"}",XContentType.JSON));
restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);