<properties>
<elasticsearch.version>6.7.1</elasticsearch.version>
</properties>
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>6.7.1</version>
</dependency>
package com.stylefeng.guns.modular.es;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Configuration
public class ESConfig {
private static String clusterName="my-application";
private static String host="****";
private static Integer port=9300;
/** 构建Settings 对象 */
private static Settings settings = Settings.builder().put("cluster.name", clusterName).build();
/** TransportClient 对象, 用于连接ES集群 */
private static volatile TransportClient client;
/**
* 同步synchronized(*.class)代码块的作用和synchronized static方法作用一样,
* 对当前对应的*.class 进行持锁, static方法和.class 一样都是锁的该类本身,同一个监听器
* @return
*/
@Bean
public static TransportClient getClient(){
if(client == null){
synchronized (TransportClient.class){
client = new PreBuiltTransportClient(settings);
try {
String[] allHost = host.split(",");
for (String str:allHost) {
client.addTransportAddresses(new TransportAddress(InetAddress.getByName(str), port));
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
return client;
}
}
package com.stylefeng.guns.modular.es;
import org.apache.ibatis.annotations.Delete;
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.Response;
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.QueryBuilder;
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;
import java.util.concurrent.ExecutionException;
@RestController
public class ESController {
@Autowired
private TransportClient client;
@GetMapping("/get/people/man")
public ResponseEntity get(@RequestParam(name="id",defaultValue = "") String id){
if(id.isEmpty()){
return new ResponseEntity( HttpStatus.NOT_FOUND);
}
GetResponse response=this.client.prepareGet("people","man",id).get();
if(!response.isExists()){
return new ResponseEntity(response.getSource(), HttpStatus.NOT_FOUND);
}
return new ResponseEntity(response.getSource(), HttpStatus.OK);
}
/**
* @param date
* @param country
* @param name
* @param age
* @return
*/
@RequestMapping("/add/people/man")
@ResponseBody
public ResponseEntity add( @RequestParam(value = "date") String date,
@RequestParam(value = "country") String country,
@RequestParam(value = "name") String name,
@RequestParam(value = "age") int age
){
System.out.println("date.toString()+country+name+age"+date+country+name+age);
try{
XContentBuilder contentBuilder=XContentFactory.jsonBuilder().startObject()
.field("date",date)
.field("country",country)
.field("name",name)
.field("age",age)
.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);
}
}
@RequestMapping("/delete/people/man")
public ResponseEntity delete(String id){
DeleteResponse deleteResponse=this.client.prepareDelete("people","man",id).get();
return new ResponseEntity(deleteResponse.getResult().toString(),HttpStatus.OK);
}
@RequestMapping("/update/people/man")
public ResponseEntity update(@RequestParam String id,
@RequestParam(value = "country",required = false) String country,
@RequestParam(value = "name",required = false) String name
){
UpdateRequest updateRequest=new UpdateRequest("people","man",id);
try {
XContentBuilder builder=XContentFactory.jsonBuilder().startObject();
if(name!=null){
builder.field("name",name);
}
if(country!=null){
builder.field("country",country);
}
builder.endObject();
updateRequest.doc(builder);
}catch (IOException e){
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
try {
UpdateResponse updateResponse=this.client.update(updateRequest).get();
return new ResponseEntity(updateResponse.getResult().toString(),HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PostMapping("/query/people/man")
public ResponseEntity query(@RequestParam(name = "name",required = false)String name,
@RequestParam(name = "country",required = false)String country,
@RequestParam(name = "gt_word_count",defaultValue = "0")int gtWordCount,
@RequestParam(name = "lt_word_count",required = false)Integer ltWordCount){
BoolQueryBuilder boolQueryBuilder=QueryBuilders.boolQuery();
if(name!=null){
boolQueryBuilder.must(QueryBuilders.matchQuery("name",name));
}
if(country!=null){
boolQueryBuilder.must(QueryBuilders.matchQuery("country",country));
}
RangeQueryBuilder rangeQueryBuilder=QueryBuilders.rangeQuery("word_count").from(gtWordCount);
if(ltWordCount!=null&<WordCount>0){
rangeQueryBuilder.to(ltWordCount);
}boolQueryBuilder.filter(rangeQueryBuilder);
SearchRequestBuilder searchRequestBuilder=this.client.prepareSearch("people").setTypes("man").setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(boolQueryBuilder).setFrom(0).setSize(10);
SearchResponse response=searchRequestBuilder.get();
List<Map<String,Object>> result=new ArrayList<>();
for (SearchHit h :response.getHits()) {
result.add(h.getSourceAsMap());
}
return new ResponseEntity(result,HttpStatus.OK);
}
}