一 :首先去官网安装下载elasticsearch(https://www.elastic.co/downloads/elasticsearch)
解压之后进入bin文件,运行程序(./elasticsearch),使用浏览器访问9200端口查看是否安装成功
二: 创建spring boot项目并引入依赖
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.BUILD-SNAPSHOT</spring-cloud.version>
<elasticsearch.version>5.4.1</elasticsearch.version>
</properties>
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
</dependencies>
三: 初始化es
package com.example.kabaouser.config;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Configuration
public class MyConfig {
@Bean
public TransportClient client() throws UnknownHostException {
InetSocketTransportAddress node = new InetSocketTransportAddress(
InetAddress.getByName("192.168.0.91"),9300);
Settings settings = Settings.builder().put("cluster.name","my-application").build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(node);
return client;
}
}
四: 创建测测试使用的索引与类型
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
},
"mappings": {
"man": {
"properties": {
"name": {
"type": "keyword" //关键字
},
"age": {
"type": "integer"
},
"date": {
"type": "date", //日期类型
"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd" //规定日期格式
}
}
}
}
}
可以借助postman工具创建
五: 编写CURD代码
package com.example.kabaouser.controller;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/es")
public class TestController {
@Autowired
private TransportClient client;
@GetMapping("/get")
@ResponseBody
public ResponseEntity get(@RequestParam(name = "id",defaultValue = "") String id) {
GetResponse result = this.client.prepareGet("people","man",id).get();
if(id.isEmpty()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
if(!result.isExists()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
return new ResponseEntity(result.getSource(),HttpStatus.OK);
}
@PostMapping("/add")
@ResponseBody
public ResponseEntity add(
@RequestParam(name = "name") String name,
@RequestParam(name = "age") int age,
@RequestParam(name = "date")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date date
) {
try {
XContentBuilder contentBuilder = XContentFactory.jsonBuilder().startObject().field("name",name)
.field("age",age)
.field("date",date.getTime())
.endObject();
IndexResponse response = this.client.prepareIndex("people","man")
.setSource(contentBuilder).get();
return new ResponseEntity(response.getId(),HttpStatus.OK);
}catch (IOException e){
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@DeleteMapping("/del")
@ResponseBody
public ResponseEntity delete(@RequestParam(name = "id",defaultValue = "") String id) {
if(id.isEmpty()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
DeleteResponse response = this.client.prepareDelete("people","man",id).get();
return new ResponseEntity(response.getResult().toString(),HttpStatus.OK);
}
@PostMapping("/upd")
@ResponseBody
public ResponseEntity updateTest(
@RequestParam(name = "id",defaultValue = "") String id,
@RequestParam(name = "name",defaultValue = "") String name,
) {
if(id.isEmpty()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
System.out.println("id:" + id +" name: " + name + " country: " + country);
UpdateRequest updateRequest = new UpdateRequest("people","man",id);
try {
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject();
if(name != null) {
builder.field("name",name);
}
builder.endObject();
updateRequest.doc(builder);
}catch (IOException e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
try {
UpdateResponse response = this.client.update(updateRequest).get();
return new ResponseEntity(response.getResult().toString(),HttpStatus.OK);
}catch (Exception e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PostMapping("/query")
@ResponseBody
public ResponseEntity query(@RequestParam(name = "name" ,required = false) String name,
@RequestParam(name = "gt_age" ,defaultValue = "0") int gtAge,
@RequestParam(name = "lt_age" , required = false) Integer ltAge) {
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
if(name != null) {
boolQueryBuilder.must(QueryBuilders.matchQuery("name",name));
}
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age").from(gtAge);
if(ltAge != null && ltAge > 0) {
rangeQueryBuilder.to(ltAge);
}
boolQueryBuilder.filter(rangeQueryBuilder);
SearchRequestBuilder builder = this.client.prepareSearch("people").setTypes("man")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(boolQueryBuilder).setFrom(0).setSize(10);
System.out.println(boolQueryBuilder);
SearchResponse response = builder.get();
List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
for (SearchHit hit : response.getHits()) {
result.add(hit.getSource());
}
return new ResponseEntity(result,HttpStatus.OK);
}
}