ElasticSearch Spring Boot CRUD


<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>vip.fkandy</groupId>
	<artifactId>SpringBoot_ElasticSearch</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>SpringBoot_ElasticSearch</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.6.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<elasticsearch.version>5.5.2</elasticsearch.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>transport</artifactId>
			<version>${elasticsearch.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</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>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>https://repo.spring.io/snapshot</url>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>

	<pluginRepositories>
		<pluginRepository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>https://repo.spring.io/snapshot</url>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</pluginRepository>
		<pluginRepository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository>
	</pluginRepositories>


</project>
package vip.fkandy;

import java.net.InetAddress;
import java.net.UnknownHostException;

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;

@Configuration
public class MyConfig {

	@Bean
	public TransportClient client() throws UnknownHostException {
		InetSocketTransportAddress node = new InetSocketTransportAddress(
				InetAddress.getByName("localhost"), 9300);
		Settings settings = Settings.builder().put("cluster.name", "andy")
				.build();
		TransportClient client = new PreBuiltTransportClient(settings);
		client.addTransportAddress(node);
		return client;
	}

}

package vip.fkandy;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class SpringBootElasticSearchApplication {

	@Autowired
	private TransportClient client;
	@GetMapping("/")
	public String index() {
		return "index";
	}

	@GetMapping("/get/book/novel")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> get(
			@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);
	}

	@PostMapping("add/book/novel")
	@ResponseBody
	public ResponseEntity add(@RequestParam(name = "title") String title,
			@RequestParam(name = "author") String author,
			@RequestParam(name = "word_count") String wordCount,
			@RequestParam(name = "publish_date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date publishDate) {
		try {
			XContentBuilder content = XContentFactory.jsonBuilder()
					.startObject().field("title", title).field("author", author)
					.field("word_count", wordCount)
					.field("publish_date", publishDate.getTime()).endObject();

			IndexResponse response = this.client.prepareIndex("book", "novel")
					.setSource(content).get();
			return new ResponseEntity(response.getId(), HttpStatus.OK);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@DeleteMapping("delete/book/novel")
	@ResponseBody
	public ResponseEntity delete(@RequestParam(name = "id") String id) {
		DeleteResponse response = this.client.prepareDelete("book", "novel", id)
				.get();
		return new ResponseEntity(response.getResult().toString(),
				HttpStatus.OK);
	}

	@PutMapping("update/book/novel")
	@ResponseBody
	public ResponseEntity update(@RequestParam(name = "id") String id,
			@RequestParam(name = "title", required = false) String title,
			@RequestParam(name = "author", required = false) String author) {

		UpdateRequest update = new UpdateRequest("book", "novel", id);
		try {
			XContentBuilder builder = XContentFactory.jsonBuilder()
					.startObject();
			if (title != null) {
				builder.field("title", title);
			}
			if (author != null) {
				builder.field("author", author);
			}
			builder.endObject();
			update.doc(builder);
		} catch (Exception 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 (InterruptedException | ExecutionException e) {
			e.printStackTrace();
			return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@PostMapping("query/book/novel")
	@ResponseBody
	public ResponseEntity query(
			@RequestParam(name = "author", required = false) String author,
			@RequestParam(name = "title", required = false) String title,
			@RequestParam(name = "gt_word_count", defaultValue = "0") int gtWordCount,
			@RequestParam(name = "lt_word_count", 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 rangeQuery = QueryBuilders.rangeQuery("word_count")
				.from(gtWordCount);
		if (ltWordCount != null && ltWordCount > 0) {
			rangeQuery.to(ltWordCount);
		}
		boolQuery.filter(rangeQuery);
		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<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		for (SearchHit hit : response.getHits()) {
			result.add(hit.getSource());
		}
		return new ResponseEntity(result, HttpStatus.OK);
	}

	public static void main(String[] args) {
		SpringApplication.run(SpringBootElasticSearchApplication.class, args);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值