说明:本文章主要是简单整合和简单增删改查。
1.pom.xml
<?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><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>org.example</groupId><artifactId>EsDemo</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.10</version></dependency><!-- swagger --><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>2.0.9</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency></dependencies></project>
2.application.yml
spring:elasticsearch:rest:uris: http://192.168.18.154:9200
3.App.java
package org.example;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class App {public static void main(String[] args) {SpringApplication.run(App.class, args);}
}
4.SwaggerConfig.java
package org.example.config;import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;import java.util.ArrayList;
import java.util.List;/*** @author 李庆伟*/
@ConditionalOnWebApplication
@Configuration
@EnableSwagger2WebMvc
@EnableKnife4j
public class SwaggerConfig {/*** Swagger2的配置文件,这里可以配置Swagger2的一些基本的内容,比如扫描的包等等* []* @return {@link Docket}* @throws* @author 李庆伟*/@Beanpublic Docket createRestApi() {//设置请求在父类方法中,如果在本类方法中设置请求头,则覆盖父类方法List<Parameter> pars = makeHeader();return new Docket(DocumentationType.SWAGGER_2).select()//多包扫描.apis(RequestHandlerSelectors.basePackage(makeScanOne()))//.or(RequestHandlerSelectors.basePackage(makeScanTwo()))//.or(RequestHandlerSelectors.basePackage(makeScanThree())))//.apis(RequestHandlerSelectors.basePackage(App8300.class.getPackage().getName())).build().globalOperationParameters(pars).apiInfo(apiInfo());}/*** swagger封装请求头* [pars]* @return {@link List< Parameter>}* @throws* @author 李庆伟*/public List<Parameter> makeHeader(){List<Parameter> pars = new ArrayList<>();ParameterBuilder token = new ParameterBuilder();token.name("Authorization").description("Authorization").modelRef(new ModelRef("string")).parameterType("header").required(false).build();pars.add(token.build());ParameterBuilder languageCode = new ParameterBuilder();languageCode.name("languageCode").description("languageCode").modelRef(new ModelRef("string")).parameterType("header").required(false).build();pars.add(languageCode.build());return pars;}public String makeScanOne(){return "org.example.controller";}/*** 构建API文档的详细信息函数* @return*/public ApiInfo apiInfo() {return new ApiInfoBuilder().title(makeApiName()).version("1.0").build();}public String makeApiName(){return "文档服务接口-API";}}
5.EsBook.java
package org.example.entity;import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;import java.util.Date;@Data
@Document(indexName = "es_book_index",type = "xiyouji")
//indexName相当于数据库 type相当于表 实体属性相当于表的字段
public class EsBook {@Idprivate String id;//章节@Field(store = true, type = FieldType.Keyword)private String title;//章节名称@Field(store = true, type = FieldType.Keyword)private String code;//章节编码}
6.IndexController.java
package org.example.controller;import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.example.entity.EsBook;
import org.example.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
@RequestMapping("/index")
@Api(value = "索引_相当于数据库", tags = "索引_相当于数据库")
public class IndexController {@Autowiredprivate IndexService indexService;/*** 添加* @return {@link }* @throws* @author* @date*/@PostMapping(value = "/add")@ApiOperation(value = "添加", notes = "添加", produces = "application/json")public String add(EsBook esBook) {indexService.add(esBook);return "ok";}/*** 修改* @return {@link }* @throws* @author* @date*/@PostMapping(value = "/update")@ApiOperation(value = "修改", notes = "修改", produces = "application/json")public String update(EsBook esBook) {indexService.update(esBook);return "ok";}/*** 查询* @return {@link }* @throws* @author* @date*/@PostMapping(value = "/query")@ApiOperation(value = "查询", notes = "查询", produces = "application/json")public List<EsBook> findQuery(EsBook esBook) {List<EsBook> list = indexService.findListByQuery(esBook);return list;}/*** 分页* @return {@link }* @throws* @author* @date*/@PostMapping(value = "/findByPage")@ApiOperation(value = "分页查询", notes = "分页查询", produces = "application/json")public Page<EsBook> findByPage(@ApiParam(required = true, value = "pageNo") @RequestParam(value = "pageNo", required = true) Integer pageNo,@ApiParam(required = true, value = "pageSize") @RequestParam(value = "pageSize", required = true) Integer pageSize,@ApiParam(required = false, value = "title") @RequestParam(value = "title", required = false) String title) {Page<EsBook> list = indexService.findByPage(pageNo, pageSize, title);return list;}/*** 详情* @return {@link }* @throws* @author* @date*/@PostMapping(value = "/show")@ApiOperation(value = "详情", notes = "详情", produces = "application/json")public EsBook show(@ApiParam(required = true, value = "章节名称") @RequestParam(value = "id", required = true) String id) {EsBook es = indexService.get(id);return es;}/*** 删除* @return {@link }* @throws* @author* @date*/@PostMapping(value = "/delete")@ApiOperation(value = "删除", notes = "删除", produces = "application/json")public String delete(@ApiParam(required = true, value = "章节名称") @RequestParam(value = "id", required = true) String id) {indexService.delete(id);return "ok";}}
7.IndexService.java
package org.example.service;import org.example.entity.EsBook;
import org.springframework.data.domain.Page;import java.util.List;public interface IndexService {void add(EsBook esBook);void delete(String id);void update(EsBook esBook);List<EsBook> findListByQuery(EsBook esBook);EsBook get(String id);Page<EsBook> findByPage(Integer pageNo, Integer pageSize, String title);
}
8.IndexServiceImpl.java
package org.example.service.impl;import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.example.entity.EsBook;
import org.example.mapper.EsBookMapper;
import org.example.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;@Service
public class IndexServiceImpl implements IndexService {@Autowiredprivate EsBookMapper esBookMapper;@Overridepublic void add(EsBook esBook) {esBook.setId(UUID.randomUUID().toString().replace("-", ""));esBookMapper.save(esBook);}@Overridepublic void update(EsBook esBook) {esBookMapper.save(esBook);}@Overridepublic List<EsBook> findListByQuery(EsBook esBook) {List<EsBook> list = new ArrayList<>();BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();queryBuilder.must(QueryBuilders.termQuery("title", esBook.getTitle()));Iterable<EsBook> it = esBookMapper.search(queryBuilder);it.forEach(e->list.add(e));return list;}@Overridepublic EsBook get(String id) {try {return esBookMapper.findById(id).get();} catch (Exception e) {e.printStackTrace();}return null;}@Overridepublic Page<EsBook> findByPage(Integer pageNo, Integer pageSize, String title) {SearchQuery searchQuery = new NativeSearchQueryBuilder()// .withQuery(QueryBuilders.matchPhraseQuery("name", kw)).withPageable(PageRequest.of(pageNo, pageSize)).build();return esBookMapper.search(searchQuery);}@Overridepublic void delete(String id) {EsBook esBook = new EsBook();esBook.setId(id);esBookMapper.delete(esBook);}}
9.EsBookMapper.java
package org.example.mapper;import org.example.entity.EsBook;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;public interface EsBookMapper extends ElasticsearchRepository<EsBook,String> {}
总结一下,记录一点点。。。。。。。。。。。。。。