springboot集成elasticsearch
正文前先来一波福利推荐:
福利一:
百万年薪架构师视频,该视频可以学到很多东西,是本人花钱买的VIP课程,学习消化了一年,为了支持一下女朋友公众号也方便大家学习,共享给大家。
福利二:
毕业答辩以及工作上各种答辩,平时积累了不少精品PPT,现在共享给大家,大大小小加起来有几千套,总有适合你的一款,很多是网上是下载不到。
获取方式:
微信关注 精品3分钟 ,id为 jingpin3mins,关注后回复 百万年薪架构师 ,精品收藏PPT 获取云盘链接,谢谢大家支持!
------------------------正文开始---------------------------
在基础阶段学习ES一般是首先是 安装ES后借助 Kibana 来进行CURD 了解ES的使用;
在进阶阶段可以需要学习ES的底层原理,如何通过Version来实现乐观锁保证ES不出问题等核心原理;
第三个阶段就是学以致用 ,在项目中如何做到 springboot集成elasticsearch来解决实际问题,下边通过一个Demo的介绍过程来引导学习。
1、首先pom.xml配置所需jar包,jar使用的版本需要和测试环境上的es保持配套;
<!-- elasticsearch .x 依赖 -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency> <dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>${elasticsearch.version}</version>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!-- <scope>test</scope> -->
</dependency>
2、配置类:
@Configuration
public class ESConfiguration implements FactoryBean<TransportClient>, InitializingBean, DisposableBean { private static final Logger logger = LoggerFactory.getLogger(ESConfiguration.class); /**
* es集群地址
*/
@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; private TransportClient client; @Override
public void destroy() throws Exception {
try {
logger.info("Closing elasticSearch client");
if (client != null) {
client.close();
}
} catch (final Exception e) {
logger.error("Error closing ElasticSearch client: ", e);
}
} @Override
public TransportClient getObject() throws Exception {
return client;
} @Override
public Class<TransportClient> getObjectType() {
return TransportClient.class;
} @Override
public boolean isSingleton() {
return false;
} @Override
public void afterPropertiesSet() throws Exception {
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(); client = new PreBuiltTransportClient(esSetting);
InetSocketTransportAddress inetSocketTransportAddress = new InetSocketTransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port));
client.addTransportAddresses(inetSocketTransportAddress); } catch (Exception e) {
logger.error("elasticsearch TransportClient create error!!!", e);
}
} }
3、涉及controller层
@RestController
@RequestMapping("/search")
public class SearchRestController extends BaseController{ private static final Logger log = LoggerFactory.getLogger(SearchRestController.class); @Autowired
private ESSearchService esSearchService; @Autowired
private ESAggsSearchService eSAggsSearchService; @Autowired
private ESSuggestSearchService esSuggestSearchService; /**
* 关键字查询
* @param index
* @return
*/
@RequestMapping(value = "/test")
public ResponseVo<?> test(
@RequestParam(value = "index", required = false) String index,
@RequestParam(value = "filed", required = false) String filed,
@RequestParam(value = "keyWord", required = false) String keyWord
) throws Exception{
//判空
List<String> searchList = esSearchService.searchMessageByKeyWord(index, filed, keyWord, , );
return generateResponseVo(ESWebStatusEnum.SUCCESS, searchList);
} /**
* 构建索引
* @param index
* @return
*/
@RequestMapping(value = "/buildIndex")
public ResponseVo<?> buildIndex(@RequestParam(value = "index", required = false) String index)
{
//判空
if(index == null) {
return generateResponseVo(ESWebStatusEnum.FAILED, null);
}
esSearchService.buildIndex(index);
return generateResponseVo(ESWebStatusEnum.SUCCESS, null);
} /*@RequestMapping(value = "/delIndex")
public ResponseVo<?> delIndex(
) { for(int j=1; j<7; j++) {
for(int i=1; i<=30; i++) {
StringBuilder sb = new StringBuilder("forum2018-0");
sb.append(j);
sb.append("-"); if(i < 10) {
sb.append("0" + i);
}else {
sb.append(i);
}
try {
esSearchService.delIndex(sb.toString());
}catch(Exception e) {
System.out.println("继续");
}
}
} return generateResponseVo(ESWebStatusEnum.SUCCESS, null);
}*/ /**
* 查询数据
*
* @param index
* @param type
* @param id
* @return
*/
//http://localhost:8088/search/data?index=suggest_term_index$type=tech&id=AWpNa9UkTc7xOmAB67Cu
@RequestMapping(value = "/data")
@ResponseBody
public ResponseVo<?> search(
@RequestParam(value = "index", required = false) String index,
@RequestParam(value = "type", required = false) String type,
@RequestParam(value = "id", required = false) String id
) {
//判空
if(index == null || type == null || id == null) {
return generateResponseVo(ESWebStatusEnum.FAILED, null);
}
//搜索具体的数据来源
Map<String, Object> returnMap = esSearchService.searchDataByParam("suggest_term_index", "tech", "AWpNa9UkTc7xOmAB67Cu");
return generateResponseVo(ESWebStatusEnum.SUCCESS, returnMap);
} /**
* 增加索引
* @return
* @throws Exception
*/
@RequestMapping(value = "/build_suggest_index")
@ResponseBody
public ResponseVo<?> build_suggest_index(
) throws Exception {
//搜索具体的数据来源 // String index = "search_suggest_index";
String term_index = "suggest_term_index";
esSuggestSearchService.buildIndexByParam(term_index); return generateResponseVo(ESWebStatusEnum.SUCCESS, null); } /**
* 加入数据
* @return
* @throws Exception
*/
@RequestMapping(value = "/addDataToIndex")
@ResponseBody
public ResponseVo<?> addDataToIndexForSuggest() throws Exception
{
String term_index = "suggest_term_index"; //搜索具体的数据来源
SuggestModel data = new SuggestModel();
data.setContent("联合信用股份有限公司");//北京联合信用投资咨询有限公司,联合信用投资咨询有限公司
data.setId(1l);
data.setData(); esSuggestSearchService.addDataDocForSuggest( term_index, "tech", data); SuggestModel data1 = new SuggestModel();
data1.setContent("北京联合信用投资咨询有限公司");//,联合信用投资咨询有限公司
data1.setId(1l);
data1.setData(); esSuggestSearchService.addDataDocForSuggest( term_index, "tech", data1); SuggestModel data2 = new SuggestModel();
data2.setContent("联合信用投资咨询有限公司");//,
data2.setId(1l);
data2.setData();
esSuggestSearchService.addDataDocForSuggest( term_index, "tech", data2); return generateResponseVo(ESWebStatusEnum.SUCCESS, null);
} /**
* JSON格式化插入数据
* @return
* @throws Exception
*/
@RequestMapping(value = "/addJSONDataDoc")
@ResponseBody
public ResponseVo<?> addJSONDataDoc() throws Exception
{
String index = "bbs_post_index"; ModelMap map = new ModelMap();
map.put("collectCount", );
map.put("commentCount", );
map.put("content", "压力测试,<a data-name=\"themeName\" href=\"#searchList?search=债券市场&type=2\" data-value=\"债券市场\" contenteditable=\"false\" class=\"comment-a\">#债券市场#</a> ,<a data-name=\"bondName\" href=\"#bondInfo/b6028d34b4b16ed2bf3513dcca91daa0\" data-value=\"b6028d34b4b16ed2bf3513dcca91daa0\" contenteditable=\"false\" class=\"comment-a\">$12进出12(120312.IB)$</a> 是发的这只债券吗? okokok,<a data-name=\"entityName\" href=\"#entityInfo/2029149\" data-value=\"2029149\" contenteditable=\"false\" class=\"comment-a\">$浙江省手工业合作社联合社$</a> 是不是和公司");
map.put("createTime", "2018-09-03 13:49:51");
map.put("downloadCount", );
map.put("forwardCount", );
map.put("id", );
map.put("isAnonymity", );
map.put("originalContent", "压力测试,#债券市场# ,$12进出12(120312.IB)$ 是发的这只债券吗? okokok,$浙江省手工业合作社联合社$ 是不是和公司");
map.put("postVariety", );
map.put("readCount", );
map.put("type", );
map.put("updateTime", "2018-09-03 13:49:51");
map.put("userId", );
map.put("valid", ); String esId = esSearchService.addJSONDataDoc(index, "post", map); return generateResponseVo(ESWebStatusEnum.SUCCESS, esId);
} /**
* 封装参数进行查询
* @return
* @throws Exception
*/
@RequestMapping(value = "/getSearchByParam")
@ResponseBody
public ResponseVo<?> getSearchByParam(
) throws Exception {
//搜索具体的数据来源 BasicSearchParam param = new BasicSearchParam();
param.setIndex("bbs_post_index");
param.setField("content");
param.setDistictField("id");
param.setKeyWord("压力测试");
param.setLimit();
param.setOffset(); /*List<String> list = esSearchService.searchMsgByParam(param);
Long count = esSearchService.searchMsgCountByParam(param);
System.out.println(JSONObject.toJSONString(list));
System.out.println(count);*/ BootstrapTablePaginationVo<String> vo = eSAggsSearchService.searchMsgByParam(param); return generateResponseVo(ESWebStatusEnum.SUCCESS, vo);
} }
4、service层
@Service
public class ESAggsSearchImpl implements ESAggsSearchService { @Autowired
private ESRepository eSRepository; @Autowired
private ESAggsRepository eSAggsRepository; @Override
public BootstrapTablePaginationVo<String> searchMsgByParam(BasicSearchParam param) throws Exception {
return eSAggsRepository.searchMsgByParam(param);
} }
@Service
public class ESDeleteServiceImpl implements EsDeleteService{ @Autowired
private ESDeleteRepository esDeleteRepository; @Override
public boolean delDataById(DeleteParam esDeleteParam) {
return esDeleteRepository.delDataById(esDeleteParam);
} }
@Service
public class ESSearchServiceImpl implements ESSearchService{ @Autowired
private ESRepository eSRepository; @Autowired
private ESSuggestRepository eSSuggestRepository; @Override
public boolean buildIndex(String index) {
return eSRepository.buildIndex(index);
} @Override
public int addPostDataDoc(String postId, String postContent) throws Exception {
return eSRepository.addPostDataDoc(postId, postContent);
} @Override
public String addJSONDataDoc(String index, String type, Object obj) throws Exception {
return eSRepository.addJSONDataDoc(index, type, obj);
} @Override
public void matchQuery(String keyWord, String index, int limit, int offset) throws Exception {
eSRepository.matchQuery(keyWord, index, limit, offset);
} @Override
public Map<String, Object> searchDataByParam(String index, String type, String id) {
return eSRepository.searchDataByParam(index, type, id);
} @Override
public String addTargetDataALL(JSONObject data, String index, String type, String id) {
return eSRepository.addTargetDataALL(data, index, type, id);
} @Override
public boolean isIndexExist(String index) {
return eSRepository.isIndexExist(index);
} @Override
public Iterator<MultiGetItemResponse> multiGetData(List<Item> itemList) {
return eSRepository.multiGetData(itemList);
} @Override
public List<String> searchMessageByKeyWord(String index, String filed, String keyWord, int limit, int offset) throws Exception {
return eSRepository.searchMessageByKeyWord(index, keyWord, limit, offset);
} @Override
public List<String> searchMsgByParam(BasicSearchParam param) throws Exception {
return eSRepository.searchMsgByParam(param);
} @Override
public Long searchMsgCountByParam(BasicSearchParam param) throws Exception {
return eSRepository.searchMsgCountByParam(param);
} }
5、dao层,应该是最重要的层,主要用来进行操作es;
@Component
public class ESRepository extends BaseRepository{ private static final Logger LOG = LoggerFactory.getLogger(ESRepository.class); @Autowired
private TransportClient client; /**
* 增加文档,测试用的- 增加文档
*
* @param post
* @return
* @throws Exception
*/
public int addPostDataDoc(String postId, String postContent) throws Exception {
IndexResponse response = client.prepareIndex("forum_index", "post").setSource(XContentFactory.jsonBuilder().startObject().field("id", postId).field("content", postContent).endObject()).get();
return response.hashCode();
} /**
* 搜索
* @param param
* @return
* @throws Exception
*/
public List<String> searchMsgByParam(BasicSearchParam param) throws Exception {
String keyWord = param.getKeyWord();
String filed = param.getField();
String index = param.getIndex(); Assert.assertNotNull(client);
Assert.assertNotNull(filed);
Assert.assertNotNull(index);
Assert.assertNotNull(keyWord); //校验索引是否成功
if (!isIndexExist(index)) {
return null;
} //响应信息
List<String> responseStrList = new ArrayList<String>();
//去重的信息
CollapseBuilder cb = new CollapseBuilder(param.getDistictField()); MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(filed, keyWord);
//查询
SearchResponse response = client.prepareSearch(index)
.setQuery(matchQueryBuilder)
.setCollapse(cb)
.setFrom(param.getOffset())
.setSize(param.getLimit())
.get(); SearchHits shList = response.getHits();
for (SearchHit searchHit : shList) {
responseStrList.add(searchHit.getSourceAsString());
}
return responseStrList;
} /**
* 搜索
* @param param
* @return
* @throws Exception
*/
public Long searchMsgCountByParam(BasicSearchParam param) throws Exception {
String keyWord = param.getKeyWord();
String filed = param.getField();
String index = param.getIndex(); Assert.assertNotNull(client);
Assert.assertNotNull(filed);
Assert.assertNotNull(index);
Assert.assertNotNull(keyWord); //校验索引是否成功
if (!isIndexExist(index)) {
return null;
} //去重的信息
CollapseBuilder cb = new CollapseBuilder(param.getDistictField()); MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(filed, keyWord);
SearchResponse response = client.prepareSearch(index)
.setQuery(matchQueryBuilder)
.setCollapse(cb)
.get(); SearchHits shList = response.getHits();
return shList.totalHits;
} /**
* 查询
*
* @param keyWord
* @param index
* @param limit
* @param offset
* @return
* @throws Exception
*/
public void matchQuery(String keyWord, String index, int limit, int offset) throws Exception {
TermsQueryBuilder queryBuilder = QueryBuilders.termsQuery("content", keyWord);
SearchResponse response = client.prepareSearch(index).setQuery(queryBuilder).setFrom(offset).setSize(limit).get();
for (SearchHit searchHit : response.getHits()) {
String sourceStr = searchHit.getSourceAsString();
LOG.info("matchQuery-->>>" + sourceStr);
}
} /**
* 批量查询
*
* 备注: 1、批量查询是再你知道下面的属性的时候,才去批量查询,如果都不知道Index,type就 直接查询,那个是ES搜索,不是批量查询
* 2、批量查询能提高程序查询效率,根据需求自我添加
*
* Item 类结构里有属性,index<==>_index,type<==>_type,id<==>_id
*
* 下面是es文档结构 { "_index": "bond2018-03-15", "_type": "bond", "_id":
* "AWIoxzdzUfSIA3djz-ZK", "_score": 1, "_source": { "code": "130523",
* "@timestamp": "2018-03-15T16:29:27.214Z", "name": "15福建09", "@version":
* "1", "id": 13293, "type": "bond", "tags": [ ], "timestamp":
* "2018-03-15T16:29:27.214Z" } }
*
* @param itemList
* @return
*/
public Iterator<MultiGetItemResponse> multiGetData(List<Item> itemList) {
if (!CollectionUtils.isEmpty(itemList)) {
MultiGetRequestBuilder mgrb = client.prepareMultiGet();
itemList.forEach(item -> {
mgrb.add(item);
});
MultiGetResponse response = mgrb.get();
// 查询
Iterator<MultiGetItemResponse> itMultigetItem = response.iterator();
return itMultigetItem;
}
return null;
} /**
* 用户添加索引数据文档
*
* @param index
* 对应的数据库
* @param type
* 类型 对应mysql的数据表
* @param obj
* 可以添加目标类
* @return
* @throws Exception
*/
public int addTargetObjectDataDoc(String index, String type, Object obj) throws Exception {
// 构建参数和需要属性
Assert.assertNotNull(client);
Assert.assertNotNull(index);
Assert.assertNotNull(type);
XContentBuilder xb = XContentFactory.jsonBuilder().startObject(); // 下面是反射处理传来的Object类,对应每个字段映射到对应的索引里,如果不需要这么做的,就可以注释掉下面的代码
// 得到类对象
Class<?> userCla = (Class<?>) obj.getClass();
// 得到类中的所有属性集合
Field[] fs = userCla.getDeclaredFields();
for (int i = ; i < fs.length; i++) {// 遍历obj文档的字段字段,添加到数据里
Field f = fs[i];
f.setAccessible(true); // 设置些属性是可以访问的
Object val = new Object();
val = f.get(obj);
// 得到此属性的值
xb.field(f.getName(), val);
} // 返回数据来源 IndexResponse indexResponse = client.prepareIndex().setIndex(index).setType(type)
// .setId(id) // 如果没有设置id,则ES会自动生成一个id
.setSource(xb.endObject()).get();
LOG.info("添加document,index:" + index + ",type:" + type + ",目标类obj:" + JSONObject.toJSONString(obj));
return indexResponse.hashCode();
} /**
* 查询数据
*
* @param index
* 索引<----->关系型数据库
* @param type
* 类型<----->关系型数据表
* @param id
* 数据ID<----->id
* @return
*/
public Map<String, Object> searchDataByParam(String index, String type, String id) {
if (index == null || type == null || id == null) {
LOG.info(" 无法查询数据,缺唯一值!!!!!!! ");
return null;
}
// 来获取查询数据信息 - 查询依据: index type id
GetRequestBuilder getRequestBuilder = client.prepareGet(index, type, id);
GetResponse getResponse = getRequestBuilder.execute().actionGet();
// 这里也有指定的时间获取返回值的信息,如有特殊需求可以 return getResponse.getSource();
} /**
* 更新数据
*
* @param data
* 添加的数据类型 json格式的
* @param index
* 索引<----->关系型数据库
* @param type
* 类型<----->关系型数据表
* @param id
* 数据ID<----->id
* @return
*/
public void updateDataById(JSONObject data, String index, String type, String id) {
if (index == null || type == null || id == null) {
LOG.info(" 无法更新数据,缺唯一值!!!!!!! ");
return;
} // 更新步骤
UpdateRequest up = new UpdateRequest();
up.index(index).type(type).id(id).doc(data); // 获取响应信息
// .actionGet(timeoutMillis),也可以用这个方法,当过了一定的时间还没得到返回值的时候,就自动返回。
UpdateResponse response = client.update(up).actionGet();
LOG.info("更新数据状态信息,status{}", response.status().getStatus());
} /**
* 添加数据
*
* @param data
* 添加的数据类型 json格式的
* @param index
* 索引<----->关系型数据库
* @param type
* 类型<----->关系型数据表
* @param id
* 数据ID<----->id
* @return
*/
public String addTargetDataALL(JSONObject data, String index, String type, String id) {
// 判断一下次id是否为空,为空的话就设置一个id
if (id == null) {
id = UUID.randomUUID().toString();
}
// 正式添加数据进去
IndexResponse response = client.prepareIndex(index, type, id).setSource(data).get(); LOG.info("addTargetDataALL 添加数据的状态:{}", response.status().getStatus()); return response.getId();
} /**
* JSON字符串加入到es里
* @param index
* @param type
* @param obj
* @return
* @throws Exception
*/
public String addJSONDataDoc(String index, String type, Object obj) throws Exception{
//构建参数和需要属性
Assert.assertNotNull(client);
Assert.assertNotNull(index);
Assert.assertNotNull(type); client.prepareIndex().setIndex(index).setType(type).setSource(); //返回数据来源
IndexResponse indexResponse = client.prepareIndex().setIndex(index).setType(type).setSource(JSONObject.toJSONString(obj), XContentType.JSON).get();
LOG.debug("添加document,index:" + index + ",type:" + type + ",目标类obj:" + JSONObject.toJSONString(obj));
return indexResponse.getId();
} /**
* 判断索引是否存在
*
* @param index
* @return
*/
public boolean isIndexExist(String index) {
IndicesExistsResponse iep = client.admin().indices().exists(new IndicesExistsRequest(index)).actionGet();
if (iep.isExists()) {
LOG.info("此索引 [" + index + "] 已经在ES集群里存在");
} else {
LOG.info(" 没有此索引 [" + index + "] ");
}
return iep.isExists();
} /**
* 根据关键词查询
*
* @param keyWord
* 搜索词
* @param index
* 索引
* @param limit
* 分页参数
* @param offset
* 分页参数
* @return
* @throws Exception
*/
public List<String> searchMessageByKeyWord(String index, String keyWord, int limit, int offset) throws Exception {
List<String> responseStrList = new ArrayList<String>();
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("content", keyWord);
SearchResponse response = client.prepareSearch(index).setQuery(matchQueryBuilder).setFrom(offset).setSize(limit).get();
for (SearchHit searchHit : response.getHits()) {
responseStrList.add(searchHit.getSourceAsString());
}
return responseStrList;
} /**
* @param index
* @param filed
* @param keyWord
* @param limit
* @param offset
* @return
*/
public List<String> search_IdByKeyWord(String index, String filed, String keyWord, int limit, int offset) {
LOG.debug("es serarch index->" + index + ",filed->" + filed + ",keyWord->" + keyWord);
Assert.assertNotNull(client);
Assert.assertNotNull(index);
Assert.assertNotNull(keyWord);
List<String> responseStrList = new ArrayList<String>();
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(filed, keyWord); SearchResponse response = client.prepareSearch(index).setQuery(matchQueryBuilder).setFrom(offset).setSize(limit).get(); for (SearchHit searchHit : response.getHits()) {
responseStrList.add(searchHit.getId());
}
return responseStrList;
} /**
* 根据关键词查询,使用的查询是term_query
* @param index
* @param filed
* @param keyWord
* @param limit
* @param offset
* @return
*/
public List<String> searchMessageTermQueryByKeyWord(String index, String filed, String keyWord, int limit,
int offset) {
LOG.info("es serarch index->" + index + ",filed->" + filed + ",keyWord->" + keyWord);
Assert.assertNotNull(client);
Assert.assertNotNull(index);
Assert.assertNotNull(keyWord);
List<String> responseStrList = new ArrayList<String>();
TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery(filed, keyWord); //查询信息
SearchResponse response = client.prepareSearch(index).setQuery(termsQueryBuilder).setFrom(offset).setSize(limit).get();
for (SearchHit searchHit : response.getHits()) {
responseStrList.add(searchHit.getSourceAsString());
}
return responseStrList;
} /**
* 根据关键词查询,使用的查询是match_phrase
* @param index
* @param filed
* @param keyWord
* @param limit
* @param offset
* @return
*/
public List<String> searchMessageMatchPhraseQueryByKeyWord(String index, String filed, String keyWord, int limit,
int offset) {
LOG.info("es serarch index->" + index + ",filed->" + filed + ",keyWord->" + keyWord);
Assert.assertNotNull(client);
Assert.assertNotNull(index);
Assert.assertNotNull(keyWord);
List<String> responseStrList = new ArrayList<String>();
MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery(filed, keyWord); SearchResponse response = client.prepareSearch(index).setQuery(matchPhraseQueryBuilder).setFrom(offset).setSize(limit).get();
for (SearchHit searchHit : response.getHits()) {
responseStrList.add(searchHit.getSourceAsString());
}
return responseStrList;
} /**
* 根据关键词查询 分页查询
* @param filedMap 搜索关键词Map key 是要搜索的字段 value是关键词
* @param index 索引,库
* @param limit
* @param offset
* @param filed 字段
* @return
* @throws Exception
*/
public List<String> searchMessageByMapKeyWord(String index, Map<String, String> filedMap, int limit, int offset) throws Exception{
LOG.info("es serarch index->" + index + ",filedMap->" + JSONObject.toJSONString(filedMap));
Assert.assertNotNull(client);
Assert.assertNotNull(index);
List<String> responseStrList = new ArrayList<String>(); QueryBuilder finalQueryBuilder = null;
if(!CollectionUtils.isEmpty(filedMap)) {
for(Map.Entry<String, String> entry : filedMap.entrySet()) {
String key = entry.getKey(); //key 是要搜索的字段
String value = entry.getValue();//value是关键词 TermQueryBuilder termQueryBuilder1 = QueryBuilders.termQuery(key, value);
finalQueryBuilder = QueryBuilders.boolQuery().must(termQueryBuilder1);
}
}
//query
SearchResponse response = client.prepareSearch(index).setQuery(finalQueryBuilder).setFrom(offset).setSize(limit).get();
for (SearchHit searchHit : response.getHits()) {
responseStrList.add(searchHit.getSourceAsString());
}
return responseStrList;
} /**
* 根据关键词查询 获取总数
* @param filedMap 搜索关键词Map key 是要搜索的字段 value是关键词
* @param index 索引,库
* @param limit
* @param offset
* @param filed 字段
* @return
* @throws Exception
*/
public long searchMessageByMapKeyWordCount(String index, Map<String, String> filedMap) throws Exception{
LOG.info("es serarch index->" + index + ",filedMap->" + filedMap);
Assert.assertNotNull(client);
Assert.assertNotNull(index);
QueryBuilder finalQueryBuilder = null;
if(!CollectionUtils.isEmpty(filedMap)) {
for(Map.Entry<String, String> entry : filedMap.entrySet()) {
String key = entry.getKey(); //key 是要搜索的字段
String value = entry.getValue();//value是关键词 TermQueryBuilder termQueryBuilder1 = QueryBuilders.termQuery(key, value);
finalQueryBuilder = QueryBuilders.boolQuery().must(termQueryBuilder1);
}
}
long count = client.prepareSearch(index).setQuery(finalQueryBuilder).get().getHits().totalHits;
return count;
} public List<String> searchMessageByKeyWord(String index, String filed, String keyWord, int limit, int offset) throws Exception {
List<String> responseStrList = new ArrayList<String>();
TermQueryBuilder matchQueryBuilder = QueryBuilders.termQuery(filed, keyWord);
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("userId", "");
QueryBuilder finalQueryBuilder = QueryBuilders.boolQuery().must(matchQueryBuilder).must(termQueryBuilder); SearchResponse response = client.prepareSearch(index).setQuery(finalQueryBuilder).setFrom(offset).setSize(limit).get(); for (SearchHit searchHit : response.getHits()) {
responseStrList.add(searchHit.getSourceAsString());
}
return responseStrList;
} }
7、springboot配置文件
# Elasticsearch
elasticsearch.cluster.name=elasticsearch
elasticsearch.ip=127.0.0.1
elasticsearch.port=
elasticsearch.pool= server.port=
8、测试结果
使用浏览器进行访问结果测试:
使用kibana进行测试,结果是一样的;
--------------------- 可关注本人的公章号,每周推送精品文章
springboot集成elasticsearch的更多相关文章
- SpringBoot 集成 Elasticsearch
前面在 ubuntu 完成安装 elasticsearch,现在我们SpringBoot将集成elasticsearch. 1.创建SpringBoot项目 我们这边直接引入NoSql中Spring ...
- springboot 集成elasticsearch
In this article, we will discuss about “How to create a Spring Boot + Spring Data + Elasticsearch Ex ...
- ElasticSearch(八):springboot集成ElasticSearch集群并使用
1. 集群的搭建 见:ElasticSearch(七) 2. springboot配置集群 2.1 创建springboot项目,使用idea创建,不过多介绍(创建项目时候建议不要勾选elastics ...
- springBoot集成Elasticsearch抛出Factory method 'restHighLevelClient' threw exception; nested exception is java.lang.NoSuchFieldError: IGNORE_DEPRECATIONS
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restHighLeve ...
- ElasticSearch(十):springboot集成ElasticSearch集群完成数据的增,删,改
前言 之前介绍了使用devTools进行索引库数据的crud,这里使用的是java程序,使用中间件activeMQ进行数据库和索引库数据的同步.主要是用来完成对数据库的修改来完成对索引库的同步. 正文 ...
- Springboot 集成 ElasticSearch 踩坑
这里只涉及到基础使用 导包 <dependency> <groupId>org.springframework.boot</groupId> <artifac ...
- SpringBoot 集成Elasticsearch进行简单增删改查
一.引入的pom文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns=" ...
- springboot集成elasticsearch遇到的问题
public interface EsBlogRepository extends ElasticsearchRepository<EsBlog,String>{ Page<EsBl ...
- springboot集成elk 一: springboot + Elasticsearch
1.ELK介绍 1> Elasticsearch是实时全文搜索和分析引擎, 提供搜集.分析.存储数据三大功能: 是一套开放REST和JAVA API等结构提供高效搜索功能,可扩展的分布式系统. ...
随机推荐
- Python基础面试,看这篇文章画重点吧,Python面试题No1
为什么有这个系列的文章 一直想写一些更加基础的文章,但是总是想不到好的点子,最近到了就业季,一大堆学生面临就业了,正好,从Python的面试题出发,分析和解答一些常见的面试题,并且总结一些文字. 每一 ...
- ajax异步请求302分析
1.前言 遇到这样一种情况,打开网页两个窗口a,b(都是已经登录授权的),在a页面中退出登录,然后在b页面执行增删改查,这个时候因为授权原因,b页面后端的请求肯定出现异常(对这个异常的处理,进行内部跳 ...
- css属性分类介绍
css属性分类介绍 CSS分类目录 文本/字体/颜色 文本相关 字体相关 颜色相关 背景相关 大小/布局 大小属性 margin 外边距 padding 内边距 border 边框 position ...
- java~springcloud微服务目录索引
回到占占推荐博客索引 最近写了不过关于java,spring,微服务的相关文章,今天把它整理一下,方便大家学习与参考. java~springcloud微服务~目录索引 springcloud~服务注 ...
- Java基础练习1(数据类型转换)
1.下列代码的输出结果是:()(单选) public static void main(String[] args){ double money = 3.0; money -= 2.9; System ...
- php一致性hash算法的应用
阅读这篇博客前首先你需要知道什么是分布式存储以及分布式存储中的数据分片存储的方式有哪些? 分布式存储系统设计(2)—— 数据分片 阅读玩这篇文章后你会知道分布式存储的最优方案是使用 一致性hash算法 ...
- JavaScript对象类型判断注意点
注意点 不要使用 new Number() . new Boolean() . new String() 创建包装对象:用 parseInt() 或 parseFloat() 来转换任意类型到numb ...
- openlayers4 入门开发系列之聚合图篇(附源码下载)
前言 openlayers4 官网的 api 文档介绍地址 openlayers4 api,里面详细的介绍 openlayers4 各个类的介绍,还有就是在线例子:openlayers4 官网在线例子 ...
- Vim中设置括号自动补全
1.打开用户Vim配置文件:~/.vimrc vim ~/.vimrc 2.输入以下配置: set tabstop=4 inoremap " ""<ESC>i ...
- 关于项目中ajax 操作 原生项目遇到的问题
单选框动态赋值 $('input[name=pszt][value='+val+']').attr("checked",true); 置顶的几种方式 window.scrollTo ...