博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot 调用Elasticsearch
阅读量:2490 次
发布时间:2019-05-11

本文共 8756 字,大约阅读时间需要 29 分钟。

1、项目配置

4.0.0
cn.edu.shu
ces_chenjie
0.0.1-SNAPSHOT
jar
ces_chenjie
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
1.5.7.RELEASE
UTF-8
UTF-8
1.8
5.6.3
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.elasticsearch.client
transport
5.6.3
org.apache.logging.log4j
log4j-core
2.7
org.springframework.boot
spring-boot-maven-plugin
2、新建配置类

package cn.edu.shu.ces_chenjie;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;@Configurationpublic class MyConf {    @Bean    public TransportClient client() throws UnknownHostException {        InetSocketTransportAddress node1 = new InetSocketTransportAddress(InetAddress.getByName("localhost"),                9300                );        //连接localhost的9300端口,即Elasticsearch的master        Settings settings = Settings.builder().                put("cluster.name","chenjie")//定义集群的名字,应该与Elasticsearch的master的配置保持一致                .build();        TransportClient client = new PreBuiltTransportClient(settings);//使用设置建立客户端        client.addTransportAddress(node1);        return client;    }}

3、新建Controller

package cn.edu.shu.ces_chenjie;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.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;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;@SpringBootApplication@RestControllerpublic class CesChenjieApplication {	@Autowired	private TransportClient client;//elasticsearch客户端	@RequestMapping("/")	public String index(){		return "index";	}	/***	 * GET localhost:8080/book/novel?id=1	 * @param id 书籍ID	 * @return 书籍信息	 */	@GetMapping("/book/novel")	@ResponseBody	public ResponseEntity getBookNovel(@RequestParam(name="id",defaultValue = "")String id){		if(id.isEmpty()){			return new ResponseEntity(HttpStatus.NOT_FOUND);		}		GetResponse result = this.client.prepareGet("book","novel",id).get();				if( !result.isExists()) {			return new ResponseEntity(HttpStatus.NOT_FOUND);		}		return new ResponseEntity(result.getSource(), HttpStatus.OK);	}	/**	 * 插入一条数据	 * POST localhost:8080/book/novel	 * @param title 标题 	 * @param author 作者	 * @param word_count 字数	 * @param publish_date 出版日期	 * @return 成功返回ID,失败返回错误码	 */	@PostMapping("/book/novel")	public ResponseEntity addBookNovel(			@RequestParam(name="title",defaultValue = "")String title,			@RequestParam(name="author",defaultValue = "")String author,			@RequestParam(name="word_count",defaultValue = "")Integer word_count,			@RequestParam(name="publish_date",defaultValue = "")					@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")					Date publish_date){		try {			XContentBuilder content =  XContentFactory.jsonBuilder()                    .startObject()                    .field("title",title)                    .field("author",author)                    .field("word_count",word_count)                    .field("publish_date",publish_date.getTime())                    .endObject();			IndexResponse response = this.client.prepareIndex("book","novel")					.setSource(content)					.get();			return new ResponseEntity(response.getId(), HttpStatus.OK);		} catch (IOException e) {			e.printStackTrace();			return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);		}	}	/***	 * 通过DELETE  删除	 * @param id 书籍	 * @return	 */	@DeleteMapping("/book/novel")	public ResponseEntity delBookNovel(@RequestParam(name="id",defaultValue = "")String id){		if(id.isEmpty()){			return new ResponseEntity(HttpStatus.NOT_FOUND);		}		DeleteResponse response = client.prepareDelete("book","novel",id).get();		return new ResponseEntity(response.getResult().toString(), HttpStatus.OK);	}	/***	 * 通过PUT修改	 * @param id 书籍	 * @param title	 * @param author	 * @param word_count	 * @param publish_date	 * @return	 */	@PutMapping("/book/novel")	public ResponseEntity updateBookNovel(			@RequestParam(name="id",defaultValue = "")String id,			@RequestParam(name="title",required = false)String title,			@RequestParam(name="author",required = false)String author,			@RequestParam(name="word_count",required = false)Integer word_count,			@RequestParam(name="publish_date",required = false)				@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date publish_date){		if(id.isEmpty()){			return new ResponseEntity(HttpStatus.NOT_FOUND);		}		UpdateRequest update = new UpdateRequest("book","novel",id);		try {			XContentBuilder content =  XContentFactory.jsonBuilder()                    .startObject();			if(title != null)				content.field("title",title);			if(author != null)				content.field("author",author);			if(word_count != null)				content.field("word_count",word_count);			if(publish_date != null)				content.field("publish_date",publish_date.getTime());			content.endObject();			update.doc(content);		} catch (IOException e) {			e.printStackTrace();			return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);		}		try {			UpdateResponse response =  this.client.update(update).get();			return new ResponseEntity(response.getResult().toString(),HttpStatus.OK);		} catch (Exception e) {			e.printStackTrace();			return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);		}	}	/***	 * 通过POST进行复合查询	 * @param title	 * @param author	 * @param gtWordCount	 * @param ltWordCount	 * @return	 */	@PostMapping("book/novel/query")	public ResponseEntity query(			@RequestParam(name="title",required = false)String title,			@RequestParam(name="author",required = false)String author,			@RequestParam(name="gt_word_count",defaultValue = "0")Integer gtWordCount,			@RequestParam(name="lt_word_count",defaultValue = "0",required = false)Integer ltWordCount			){		BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();		if(author != null){			boolQuery.must(QueryBuilders.matchQuery("author",author));		}		if(title != null){			boolQuery.must(QueryBuilders.matchQuery("title",title));		}		RangeQueryBuilder range = QueryBuilders.rangeQuery("word_count");		if(ltWordCount != null && ltWordCount >0){			range.to(ltWordCount);		}		boolQuery.filter(range);		SearchRequestBuilder builder = this.client.prepareSearch("book")				.setTypes("novel")				.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)				.setQuery(boolQuery)				.setFrom(0)				.setSize(10);		System.out.println(builder);		SearchResponse response = builder.get();		List
> result = new ArrayList
>(); for(SearchHit hit:response.getHits()){ result.add(hit.getSource()); } return new ResponseEntity(result,HttpStatus.OK); } public static void main(String[] args) { SpringApplication.run(CesChenjieApplication.class, args); }}

4、使用POSTMAN测试

你可能感兴趣的文章
vnpy通过jqdatasdk初始化实时数据及历史数据下载
查看>>
设计模式19_状态
查看>>
设计模式20_观察者
查看>>
vnpy学习10_常见坑02
查看>>
用时三个月,终于把所有的Python库全部整理了!拿去别客气!
查看>>
pd.stats.ols.MovingOLS以及替代
查看>>
vnpy学习11_增加测试评估指标
查看>>
资金流入流出计算方法
查看>>
海龟交易法则07_如何衡量风险
查看>>
海龟交易法则08_风险与资金管理
查看>>
海龟交易法则09_海龟式积木
查看>>
海龟交易法则10_通用积木
查看>>
海龟交易法则14_掌控心魔
查看>>
海龟交易法则16_附原版海龟交易法则
查看>>
克罗谈投资策略01_期货交易中的墨菲法则
查看>>
克罗谈投资策略02_赢家和输家
查看>>
克罗谈投资策略03_你所期望的赌博方式
查看>>
克罗谈投资策略04_感觉与现实
查看>>
通向财务自由之路01_导读
查看>>
通向财务自由之路02_成功的决定因素:你
查看>>