ElasticSearch版本:7.6.2
首先構建maven項目,導入依賴:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.tc</groupId>
<artifactId>elasticsearch-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>elasticsearch-api</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>2.3.1.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
聲明一個Rest客戶端作爲Bean:
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
return client;
}
}
索引相關操作:
package com.tc.elasticsearchapi.controller;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.io.IOException;
@RestController
public class IndexController {
@Resource
public RestHighLevelClient restHighLevelClient;
@RequestMapping("/createIndex")
@ResponseBody
public String createIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("i_index");
CreateIndexResponse createIndexResponse = restHighLevelClient.
indices().create(request, RequestOptions.DEFAULT);
return createIndexResponse.toString();
}
@RequestMapping("/isExist")
@ResponseBody
public String indexIsExist(String index) throws IOException {
GetIndexRequest request = new GetIndexRequest(index);
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
return "status:"+exists;
}
@RequestMapping("/delete")
@ResponseBody
public String indexDelete(String index) throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest(index);
AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
return delete.isAcknowledged()?"success":"failed";
}
}
文檔相關操作:
package com.tc.elasticsearchapi.controller;
import com.alibaba.fastjson.JSON;
import com.tc.elasticsearchapi.entity.User;
import org.apache.lucene.index.IndexReader;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* 文檔操作
*/
@RestController
public class DocumentController {
@Resource
public RestHighLevelClient client;
/**
* 創建文檔
*/
@ResponseBody
@RequestMapping("/createDocument")
public String createDocument(String index) throws IOException {
User user = new User(1,"anroy");
//創建請求
IndexRequest request = new IndexRequest(index);
request.id("1");
request.timeout("1s");
request.source(JSON.toJSONString(user), XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
return response.toString();
}
/**
* 判斷文檔是否存在
*/
@ResponseBody
@RequestMapping("/docIsExist")
public String docIsExist(String index,String id) throws IOException {
GetRequest request = new GetRequest(index,id);
//不獲取返回的上下文信息
// request.fetchSourceContext(new FetchSourceContext(false));
request.storedFields("_none_");
boolean exists = client.exists(request, RequestOptions.DEFAULT);
return exists?"true":"false";
}
/**
* 獲取文檔
*/
@ResponseBody
@RequestMapping("/getDoc")
public String getDoc(String index,String id) throws IOException {
GetRequest request = new GetRequest(index,id);
GetResponse response = client.get(request, RequestOptions.DEFAULT);
//打印全部內容
System.out.println(response);
//文檔格式
return response.getSourceAsString();
}
/**
* 更新文檔
*/
@ResponseBody
@RequestMapping("/updateDoc")
public String updateDoc(String index,String id) throws IOException {
UpdateRequest request = new UpdateRequest(index,id);
User user = new User(2,"ljq");
request.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse update = client.update(request, RequestOptions.DEFAULT);
return update.toString();
}
/**
* 批量插入
*/
@ResponseBody
@RequestMapping("/bulkRequest")
public String bulkRequest(String index,String id) throws IOException {
BulkRequest request = new BulkRequest();
request.timeout("10s");
List<User> list = new ArrayList<>();
list.add(new User(2,"ljq1"));
list.add(new User(3,"ljq3"));
list.add(new User(4,"ljq4"));
for (int i=0;i<list.size();i++){
request.add(new IndexRequest(index).id(""+(i+1))
.source(JSON.toJSONString(list.get(i)),XContentType.JSON));
}
BulkResponse bulk = client.bulk(request, RequestOptions.DEFAULT);
return !bulk.hasFailures()?"success":"failed";
}
/**
* 查詢請求
* http://localhost:8080/search?index=i_index&name=name&value=ljq1
*/
@RequestMapping("/search")
public String search(String index,String name,String value) throws IOException {
SearchRequest request = new SearchRequest(index);
//構建搜索條件
SearchSourceBuilder builder = new SearchSourceBuilder();
//查詢條件,可以使用 QueryBuilders
//精確查詢用termQuery
//查詢全部用 QueryBuilders.matchAllQuery()
TermQueryBuilder query = QueryBuilders.termQuery(name, value);
builder.query(query);
builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(response.getHits()));
// SearchHit[] hits = response.getHits().getHits();
for(SearchHit fields:response.getHits().getHits()){
System.out.println(fields.getSourceAsMap());
}
return response.status().toString();
}
}
操作的結果可以在head插件中看到: