我是靠谱客的博主 贪玩冬天,最近开发中收集的这篇文章主要介绍spring boot2.0 集成ES6.4.2,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

application.properties

# Elasticsearch
# 9200端口是用来让HTTP REST API来访问ElasticSearch,而9300端口是传输层监听的默认端口
elasticsearch.ip=127.0.0.1
elasticsearch.port=9300
elasticsearch.pool=5
#注意cluster.name需要与config/elasticsearch.yml中的cluster.name一致
elasticsearch.cluster.name=elasticsearch

pox

 <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.elasticsearch.plugin/transport-netty4-client -->
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>6.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.4.2</version>
<!--
<exclusions>-->
<!--
<exclusion>-->
<!--
<groupId>org.elasticsearch</groupId>-->
<!--
<artifactId>elasticsearch</artifactId>-->
<!--
</exclusion>-->
<!--
</exclusions>-->
</dependency>

##配置类 ElasticSearchConfig

package com.demo.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
@Configuration
public class ElasticSearchConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(ElasticSearchConfig.class);
/**
* elk集群地址
*/
@Value("${elasticsearch.ip}")
private String hostName;
/**
* 端口
*/
@Value("${elasticsearch.port}")
private String port;
/**
* 集群名称
*/
@Value("${elasticsearch.cluster.name}")
private String clusterName;
/**
* 连接池
*/
@Value("${elasticsearch.pool}")
private String poolSize;
/**
* Bean name default
函数名字
*
* @return
*/
@Bean(name = "transportClient")
public TransportClient transportClient() {
LOGGER.info("Elasticsearch初始化开始。。。。。");
TransportClient transportClient = null;
try {
// 配置信息
Settings esSetting = Settings.builder()
.put("cluster.name", clusterName) //集群名字
.put("client.transport.sniff", true)//增加嗅探机制,找到ES集群
.put("thread_pool.search.size", Integer.parseInt(poolSize))//增加线程池个数,暂时设为5
.build();
//配置信息Settings自定义
transportClient = new PreBuiltTransportClient(esSetting);
TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port));
transportClient.addTransportAddresses(transportAddress);
} catch (Exception e) {
LOGGER.error("elasticsearch TransportClient create error!!", e);
}
return transportClient;
}
}

ES工具类 ElasticsearchUtil

package com.demo.es;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequestBuilder;
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.client.transport.TransportClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.search.MultiMatchQuery;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@Component
public class ElasticsearchUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchUtil.class);
@Autowired
private TransportClient transportClient;
private static TransportClient client;
/**
* @PostContruct是spring框架的注解 spring容器初始化的时候执行该方法
*/
@PostConstruct
public void init() {
client = this.transportClient;
}
/**
* 创建索引
*
* @param index
* @return
*/
public static boolean createIndex(String index) {
if (!isIndexExist(index)) {
LOGGER.info("Index is not exits!");
}
CreateIndexResponse indexresponse = client.admin().indices().prepareCreate(index).execute().actionGet();
LOGGER.info("执行建立成功?" + indexresponse.isAcknowledged());
return indexresponse.isAcknowledged();
}
/**
* 删除索引
*
* @param index
* @return
*/
public static boolean deleteIndex(String index) {
if (!isIndexExist(index)) {
LOGGER.info("Index is not exits!");
}
DeleteIndexResponse dResponse = client.admin().indices().prepareDelete(index).execute().actionGet();
if (dResponse.isAcknowledged()) {
LOGGER.info("delete index " + index + "
successfully!");
} else {
LOGGER.info("Fail to delete index " + index);
}
return dResponse.isAcknowledged();
}
/**
* 判断索引是否存在
*
* @param index
* @return
*/
public static boolean isIndexExist(String index) {
IndicesExistsResponse inExistsResponse = client.admin().indices().exists(new IndicesExistsRequest(index)).actionGet();
if (inExistsResponse.isExists()) {
LOGGER.info("Index [" + index + "] is exist!");
} else {
LOGGER.info("Index [" + index + "] is not exist!");
}
return inExistsResponse.isExists();
}
/**
* @Description: 判断inde下指定type是否存在
*/
public boolean isTypeExist(String index, String type) {
return isIndexExist(index)
? client.admin().indices().prepareTypesExists(index).setTypes(type).execute().actionGet().isExists()
: false;
}
/**
* 数据添加,正定ID
*
* @param jsonObject 要增加的数据
* @param index
索引,类似数据库
* @param type
类型,类似表
* @param id
数据ID
* @return
*/
public static String addData(JSONObject jsonObject, String index, String type, String id) {
IndexResponse response = client.prepareIndex(index, type, id).setSource(jsonObject).get();
LOGGER.info("addData response status:{},id:{}", response.status().getStatus(), response.getId());
return response.getId();
}
/**
* 数据添加
*
* @param jsonObject 要增加的数据
* @param index
索引,类似数据库
* @param type
类型,类似表
* @return
*/
public static String addData(JSONObject jsonObject, String index, String type) {
return addData(jsonObject, index, type, UUID.randomUUID().toString().replaceAll("-", "").toUpperCase());
}
/**
* 通过ID删除数据
*
* @param index 索引,类似数据库
* @param type
类型,类似表
* @param id
数据ID
*/
public static Integer deleteDataById(String index, String type, String id) {
DeleteResponse response = client.prepareDelete(index, type, id).execute().actionGet();
LOGGER.info("deleteDataById response status:{},id:{}", response.status().getStatus(), response.getId());
return response.status().getStatus();
}
/**
* 通过ID 更新数据
*
* @param jsonObject 要增加的数据
* @param index
索引,类似数据库
* @param type
类型,类似表
* @param id
数据ID
* @return
*/
public static Integer updateDataById(JSONObject jsonObject, String index, String type, String id) {
try {
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index(index).type(type).id(id).doc(jsonObject);
Integer status
= client.update(updateRequest).actionGet().status().getStatus();
LOGGER.info("updateDataById response status:{},id:{}", status, id);
return status;
}catch (Exception e) {
return 404;
}
}
/**
* 通过ID获取数据
*
* @param index
索引,类似数据库
* @param type
类型,类似表
* @param id
数据ID
* @param fields 需要显示的字段,逗号分隔(缺省为全部字段)
* @return
*/
public static Map<String, Object> searchDataById(String index, String type, String id, String fields) {
GetRequestBuilder getRequestBuilder = client.prepareGet(index, type, id);
if (StringUtils.isNotEmpty(fields)) {
getRequestBuilder.setFetchSource(fields.split(","), null);
}
GetResponse getResponse = getRequestBuilder.execute().actionGet();
return getResponse.getSource();
}
/**
* 使用分词查询,并分页
*
* @param index
索引名称
* @param type
类型名称,可传入多个type逗号分隔
* @param startPage
当前页
* @param pageSize
每页显示条数
* @param query
查询条件
* @param fields
需要显示的字段,逗号分隔(缺省为全部字段)
* @param sortField
排序字段
* @param highlightField 高亮字段
* @return
*/
public static EsPage searchDataPage(SortOrder px,String index, String type, int startPage, int pageSize, QueryBuilder query, String fields, String sortField, String highlightField,String text) {
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index);
if (StringUtils.isNotEmpty(type)) {
searchRequestBuilder.setTypes(type.split(","));
}
searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
// 需要显示的字段,逗号分隔(缺省为全部字段)
if (StringUtils.isNotEmpty(fields)) {
searchRequestBuilder.setFetchSource(fields.split(","), null);
}
//排序字段
if (StringUtils.isNotEmpty(sortField)) {
searchRequestBuilder.addSort(sortField, px);
}
// 高亮(xxx=111,aaa=222)
//
if (StringUtils.isNotEmpty(highlightField)) {
//
HighlightBuilder highlightBuilder = new HighlightBuilder();
//
//
highlightBuilder.preTags("<span style='color:red' >");//设置前缀
//
highlightBuilder.postTags("</span>");//设置后缀
//
// 设置高亮字段
//
highlightBuilder.field(highlightField);
//
searchRequestBuilder.highlighter(highlightBuilder);
//
System.out.println("===========================================");
//
}
//
searchRequestBuilder.setQuery(QueryBuilders.matchAllQuery());
searchRequestBuilder.setQuery(query);
// 分页应用
searchRequestBuilder.setFrom(startPage).setSize(pageSize);
// 设置是否按查询匹配度排序
searchRequestBuilder.setExplain(true);
//打印的内容 可以在 Elasticsearch head 和 Kibana
上执行查询
LOGGER.info("n{}", searchRequestBuilder);
// 执行搜索,返回搜索响应信息
SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
long totalHits = searchResponse.getHits().totalHits;
long length = searchResponse.getHits().getHits().length;
LOGGER.debug("共查询到[{}]条数据,处理数据条数[{}]", totalHits, length);
if (searchResponse.status().getStatus() == 200) {
// 解析对象
List<Map<String, Object>> sourceList = setSearchResponse(searchResponse, highlightField,text);
return new EsPage(startPage, pageSize, (int) totalHits, sourceList);
}
return null;
}
/**
* 使用分词查询
*
* @param index
索引名称
* @param type
类型名称,可传入多个type逗号分隔
* @param query
查询条件
* @param size
文档大小限制
* @param fields
需要显示的字段,逗号分隔(缺省为全部字段)
* @param sortField
排序字段
* @param highlightField 高亮字段
* @return
*/
public static List<Map<String, Object>> searchListData(
String index, String type, QueryBuilder query, Integer size,
String fields, String sortField, String highlightField) {
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index);
if (StringUtils.isNotEmpty(type)) {
searchRequestBuilder.setTypes(type.split(","));
}
if (StringUtils.isNotEmpty(highlightField)) {
HighlightBuilder highlightBuilder = new HighlightBuilder();
// 设置高亮字段
highlightBuilder.field(highlightField);
searchRequestBuilder.highlighter(highlightBuilder);
}
searchRequestBuilder.setQuery(query);
if (StringUtils.isNotEmpty(fields)) {
searchRequestBuilder.setFetchSource(fields.split(","), null);
}
searchRequestBuilder.setFetchSource(true);
if (StringUtils.isNotEmpty(sortField)) {
searchRequestBuilder.addSort(sortField, SortOrder.ASC);
}
if (size != null && size > 0) {
searchRequestBuilder.setSize(size);
}
//打印的内容 可以在 Elasticsearch head 和 Kibana
上执行查询
LOGGER.info("n{}", searchRequestBuilder);
SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
long totalHits = searchResponse.getHits().totalHits;
long length = searchResponse.getHits().getHits().length;
LOGGER.info("共查询到[{}]条数据,处理数据条数[{}]", totalHits, length);
if (searchResponse.status().getStatus() == 200) {
// 解析对象
return setSearchResponse(searchResponse, null,null);
}
return null;
}
/**
* 高亮结果集 特殊处理
*
* @param searchResponse
* @param highlightField
*/
private static List<Map<String, Object>> setSearchResponse(SearchResponse searchResponse, String highlightField,String text) {
List<Map<String, Object>> sourceList = new ArrayList<Map<String, Object>>();
//
StringBuffer stringBuffer = new StringBuffer();
for (SearchHit searchHit : searchResponse.getHits().getHits()) {
searchHit.getSourceAsMap().put("id", searchHit.getId());
if (StringUtils.isNotEmpty(highlightField)) {
LOGGER.info("遍历 高亮结果集,覆盖 正常结果集" + searchHit.getSourceAsMap());
//
Text[] text = searchHit.getHighlightFields().get(highlightField).getFragments();
//
if (text != null) {
//
for (Text str : text) {
//
stringBuffer.append(str.string());
//
}
//
//遍历 高亮结果集,覆盖 正常结果集
//
searchHit.getSourceAsMap().put(highlightField, stringBuffer.toString());
//
}
String str =
searchHit.getSourceAsMap().get(highlightField).toString().replace(text,"<span style='background-color: yellow;'>"+text+"</span>");
searchHit.getSourceAsMap().put(highlightField, str);
}
sourceList.add(searchHit.getSourceAsMap());
}
return sourceList;
}
}

Employee

package com.demo.es;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.List;
/**
* @Description:Book实体 加上了@Document注解之后,默认情况下这个实体中所有的属性都会被建立索引、并且分词
*/
@Data
@ToString
@NoArgsConstructor
public class Employee {
private Integer id;
private String name;
private String pwd;
private List<EmployeeClass> employe;
}

EmployeeClass

package com.demo.es;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.List;
/**
* @Description:Book实体 加上了@Document注解之后,默认情况下这个实体中所有的属性都会被建立索引、并且分词
*/
@Data
@ToString
@NoArgsConstructor
public class EmployeeClass {
private String phone;
}

分页工具类 EsPage

package com.demo.es;
import lombok.Data;
import lombok.ToString;
import java.util.List;
import java.util.Map;
@Data
@ToString
public class EsPage {
/**
* 当前页
*/
private int currentPage;
/**
* 每页显示多少条
*/
private int pageSize;
/**
* 总记录数
*/
private int recordCount;
/**
* 本页的数据列表
*/
private List<Map<String, Object>> recordList;
/**
* 总页数
*/
private int pageCount;
/**
* 页码列表的开始索引(包含)
*/
private int beginPageIndex;
/**
* 页码列表的结束索引(包含)
*/
private int endPageIndex;
/**
* 只接受前4个必要的属性,会自动的计算出其他3个属性的值
*
* @param currentPage
* @param pageSize
* @param recordCount
* @param recordList
*/
public EsPage(int currentPage, int pageSize, int recordCount, List<Map<String, Object>> recordList) {
this.currentPage = currentPage;
this.pageSize = pageSize;
this.recordCount = recordCount;
this.recordList = recordList;
// 计算总页码
pageCount = (recordCount + pageSize - 1) / pageSize;
// 计算 beginPageIndex 和 endPageIndex
// >> 总页数不多于10页,则全部显示
if (pageCount <= 10) {
beginPageIndex = 1;
endPageIndex = pageCount;
}
// 总页数多于10页,则显示当前页附近的共10个页码
else {
// 当前页附近的共10个页码(前4个 + 当前页 + 后5个)
beginPageIndex = currentPage - 4;
endPageIndex = currentPage + 5;
// 当前面的页码不足4个时,则显示前10个页码
if (beginPageIndex < 1) {
beginPageIndex = 1;
endPageIndex = 10;
}
// 当后面的页码不足5个时,则显示后10个页码
if (endPageIndex > pageCount) {
endPageIndex = pageCount;
beginPageIndex = pageCount - 10 + 1;
}
}
}
}

EsController接口

package com.demo.controller;
import com.alibaba.fastjson.JSONObject;
import com.demo.core.annotation.RecordLog;
import com.demo.es.ElasticsearchUtil;
import com.demo.es.Employee;
import com.demo.es.EmployeeClass;
import com.demo.es.EsPage;
import com.demo.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
@Api(tags = "案例4:ES6.4.1版本")
@RestController
@RequestMapping("/es")
public class EsController {
/**
* 测试索引
*/
private String indexName = "megacorp";
/**
* 类型
*/
private String esType = "employee";
/**
* 创建索引
* http://127.0.0.1:8080/es/createIndex
* @param request
* @param response
* @return
*/
@RecordLog
@ApiOperation(value = "创建索引")
@GetMapping(value = "/createIndex")
public String createIndex(HttpServletRequest request, HttpServletResponse response) {
if (!ElasticsearchUtil.isIndexExist(indexName)) {
ElasticsearchUtil.createIndex(indexName);
} else {
return "索引已经存在";
}
return "索引创建成功";
}
/**
* 插入记录
*
* @return
*/
//
@RecordLog
//
@ApiOperation(value = "插入记录--json")
//
@GetMapping(value = "/insertJson")
//
public String insertJson() {
//
JSONObject jsonObject = new JSONObject();
//
jsonObject.put("id", DateUtil.formatDate(new Date()));
//
jsonObject.put("age", 25);
//
jsonObject.put("first_name", "j-" + new Random(100).nextInt());
//
jsonObject.put("last_name", "cccc");
//
jsonObject.put("about", "i like xiaofeng baby");
//
jsonObject.put("date", new Date());
//
String id = ElasticsearchUtil.addData(jsonObject, indexName, esType, jsonObject.getString("id"));
//
return id;
//
}
/**
* 新增对象
*
* @return
*/
@RecordLog
@ApiOperation(value = "新增对象")
@GetMapping(value = "/insertModelObj")
public Result insertModelObj(Integer id,String name,String pwd) {
Employee employee = new Employee();
employee.setId(id);
employee.setName("用户名:"+name);
employee.setPwd("密码:"+pwd);
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(employee);
String idsa = ElasticsearchUtil.addData(jsonObject, indexName, esType, jsonObject.getString("id"));
return Result.OK(idsa);
}
/**
* 插入记录
*
* @return
*/
@RecordLog
@ApiOperation(value = "插入记录--对象")
@GetMapping(value = "/insertModel")
public Result insertModel() {
for (int i = 1; i < 100; i++) {
Employee employee = new Employee();
employee.setId(i);
employee.setName("用户名:_"+i);
employee.setPwd("密码:_"+i);
List<EmployeeClass> employe = new ArrayList<>();
EmployeeClass employeeClass = new EmployeeClass();
employeeClass.setPhone(String.valueOf(new Random(10000).nextInt()));
employe.add(employeeClass);
EmployeeClass employeeClasssa = new EmployeeClass();
employeeClasssa.setPhone(String.valueOf(new Random(10000).nextInt()));
employe.add(employeeClasssa);
employee.setEmploye(employe);
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(employee);
String id = ElasticsearchUtil.addData(jsonObject, indexName, esType, jsonObject.getString("id"));
}
return Result.OK();
}
/**
* 删除记录
*
* @return
*/
@RecordLog
@ApiOperation(value = "删除记录")
@GetMapping(value = "/delete")
public Result delete(String id) {
if (StringUtils.isNotBlank(id)) {
Integer status =
ElasticsearchUtil.deleteDataById(indexName, esType, id);
if (status==404){
return Result.error("id="+id+"不存在,删除失败!");
}
return Result.OK("id="+id+"删除成功!");
} else {
return Result.error("id为空");
}
}
/**
* 更新数据
*
* @return
*/
@RecordLog
@ApiOperation(value = "修改记录")
@GetMapping(value = "/update")
public Result update(Integer id) {
if (StringUtils.isNotBlank(String.valueOf(id))) {
Employee employee = new Employee();
employee.setId(id);
employee.setName("用户名:_张三");
employee.setPwd("密码:_张三的密码");
List<EmployeeClass> employe = new ArrayList<>();
EmployeeClass employeeClass = new EmployeeClass();
employeeClass.setPhone("1125154125");
employe.add(employeeClass);
EmployeeClass employeeClasssa = new EmployeeClass();
employeeClasssa.setPhone("18524715241");
employe.add(employeeClasssa);
employee.setEmploye(employe);
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(employee);
Integer status = ElasticsearchUtil.updateDataById(jsonObject, indexName, esType, String.valueOf(id));
if (status==404){
return Result.error("id="+id+"不存在,修改失败!");
}
return Result.OK("id="+id+"修改成功!");
} else {
return Result.error("id为空");
}
}
/**
* 获取数据
* http://127.0.0.1:8080/es/getData?id=2018-04-25%2016:33:44
* @param id
* @return
*/
@RecordLog
@ApiOperation(value = "获取数据-单条记录,逗号分割")
@GetMapping(value = "/getData")
public Result getData(String id) {
if (StringUtils.isNotBlank(id)) {
Map<String, Object> map = ElasticsearchUtil.searchDataById(indexName, esType, id, null);
return Result.OK(map);
} else {
return Result.error("id为空");
}
}
/**
* 查询分页
*
* @param pageno 第几条记录开始
*
第1页 :http://127.0.0.1:8080/es/queryPage?startPage=0&pageSize=2
*
第2页 :http://127.0.0.1:8080/es/queryPage?startPage=2&pageSize=2
* @param pageSize
每页大小
* @return
*/
@ApiImplicitParams({
@ApiImplicitParam(name = "pageno",value = "当前页",required = true, paramType = "query"),
@ApiImplicitParam(name = "pageSize",value = "显示条数",required = true, paramType = "query"),
@ApiImplicitParam(name = "name",value = "模糊查询",required = true, paramType = "query"),
@ApiImplicitParam(name = "isf",value = "是否分词,1分",required = true, paramType = "query"),
})
@RecordLog
@ApiOperation(value = "查询分页")
@GetMapping(value = "/queryPage")
public Result queryPage(Integer pageno, Integer pageSize,String name,Long isf) {
if (StringUtils.isNotBlank(String.valueOf(pageno)) && StringUtils.isNotBlank(String.valueOf(pageSize))) {
if (pageno==1){
pageno = 0;
}else{
pageno = pageno * pageSize;
}
if(pageSize<=0){
pageSize = 1;
}
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
if (StringUtils.isNotBlank(name)){
if (isf==1L){
boolQuery.must(QueryBuilders.matchQuery("name", name));
}else{
boolQuery.must(QueryBuilders.matchPhraseQuery("name", name));
}
}
//
boolQuery.must(QueryBuilders.rangeQuery("age").from("20").to("100"));//闭区间
//
boolQuery.must(QueryBuilders.rangeQuery("age").from(20,false).to(100,false));//开区间
//
索引名称
索引类型
当前页
显示页
查询条件
需要显示的字段,逗号分隔(缺省为全部字段)
排序字段
高亮字段
高亮值
EsPage list = ElasticsearchUtil.searchDataPage(SortOrder.ASC,indexName, esType, Integer.parseInt(String.valueOf(pageno)), Integer.parseInt(String.valueOf(pageSize)), boolQuery, null, "id", "name","用户");
//
return JSONObject.toJSONString(list);
return Result.OK(list);
} else {
return Result.error( "startPage或者pageSize缺失");
}
}
/**
* 查询数据
* 模糊查询
*
* @return
*/
//
@ApiImplicitParams({
//
@ApiImplicitParam(name = "name",value = "姓名查询",required = true, paramType = "query"),
//
})
//
@RecordLog
//
@ApiOperation(value = "模糊查询")
//
@GetMapping(value = "/queryMatchData")
//
public Result queryMatchData(String name,Long id) {
//
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//
boolean matchPhrase = false;
//
if (id==1L){
//
matchPhrase = true;
//
}
//
if (matchPhrase == Boolean.TRUE) {
//
//不进行分词搜索
//
boolQuery.must(QueryBuilders.matchPhraseQuery("name", name));
//
} else {
//
boolQuery.must(QueryBuilders.matchQuery("name", name));
//
}
//
List<Map<String, Object>> list = ElasticsearchUtil.
//
searchListData(indexName, esType, boolQuery, 10, "name", null, "name");
//
//
return Result.OK(list);
//
}
/**
* 通配符查询数据
* 通配符查询 ?用来匹配1个任意字符,*用来匹配零个或者多个字符
*
* @return
*/
//
@RecordLog
//
@ApiOperation(value = "通配符查询数据-通配符查询 ?用来匹配1个任意字符,*用来匹配零个或者多个字符")
//
@GetMapping(value = "/queryWildcardData")
//
public String queryWildcardData() {
//
QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("first_name.keyword", "cici");
//
List<Map<String, Object>> list = ElasticsearchUtil.searchListData(indexName, esType, queryBuilder, 10, null, null, null);
//
return JSONObject.toJSONString(list);
//
}
/**
* 正则查询
*
* @return
*/
//
@RecordLog
//
@ApiOperation(value = "正则查询")
//
@GetMapping(value = "/queryRegexpData")
//
public String queryRegexpData() {
//
QueryBuilder queryBuilder = QueryBuilders.regexpQuery("first_name.keyword", "m--[0-9]{1,11}");
//
List<Map<String, Object>> list = ElasticsearchUtil.searchListData(indexName, esType, queryBuilder, 10, null, null, null);
//
return JSONObject.toJSONString(list);
//
}
/**
*查询数字范围数据
* @return
*/
//
@RecordLog
//
@ApiOperation(value = "查询数字范围数据")
//
@GetMapping(value = "/queryIntRangeData")
//
public String queryIntRangeData() {
//
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//
boolQuery.must(QueryBuilders.rangeQuery("age").from(24)
//
.to(25));
//
List<Map<String, Object>> list = ElasticsearchUtil.searchListData(indexName, esType, boolQuery, 10, null, null, null);
//
return JSONObject.toJSONString(list);
//
}
/**
* 查询日期范围数据
*
* @return
*/
//
@RecordLog
//
@ApiOperation(value = "查询日期范围数据")
//
@GetMapping(value = "/queryDateRangeData")
//
public String queryDateRangeData() {
//
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//
boolQuery.must(QueryBuilders.rangeQuery("age").from("20")
//
.to("50"));
//
List<Map<String, Object>> list = ElasticsearchUtil.searchListData(indexName, esType, boolQuery, 10, null, null, null);
//
return JSONObject.toJSONString(list);
//
}
}

最后

以上就是贪玩冬天为你收集整理的spring boot2.0 集成ES6.4.2的全部内容,希望文章能够帮你解决spring boot2.0 集成ES6.4.2所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部