• service
package com.huarui.service;

import com.huarui.entity.SearchEntity;
import com.huarui.exection.JestExcetion;
import io.searchbox.client.JestResult;
import org.elasticsearch.index.query.QueryBuilder; import java.util.List; /**
* Created by lihui on 2019/1/30.
*/
public interface JestClientService { <T extends SearchEntity> JestResult index(T t, String indexKey) throws JestExcetion; JestResult delete(String id)throws JestExcetion; <T extends SearchEntity> T get(String id, Class<T> clazz) throws JestExcetion; JestResult deleteIndex() throws JestExcetion; /*********************我是分割线************************/ <T extends SearchEntity> JestResult indexBatch(List<T> t) throws JestExcetion; <T extends SearchEntity> List<T> pageSearch(int from, int size, QueryBuilder queryBuilder,Class<T> clazz)
throws JestExcetion; <T extends SearchEntity> List<T> search(QueryBuilder queryBuilder,Class<T> clazz) throws JestExcetion; Double count(QueryBuilder queryBuilder) throws JestExcetion; }

JestClientService.java

package com.huarui.service.impl;

import com.huarui.entity.SearchEntity;
import com.huarui.exection.JestExcetion;
import com.huarui.service.JestClientService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.List; /**
* Created by lihui on 2019/1/30.
* JestClient 操作类
*/
@Service
public class JestClientServiceImpl implements JestClientService { private static Logger LOGGER = LoggerFactory.getLogger(JestClientServiceImpl.class); @Autowired
private JestClient jestClient; private String indexName = "test";//索引名称
private String indexType = "books";//文档类型 /**
* 创建索引
* @param t
* @param indexKey
* @param <T>
* @return
* @throws JestExcetion
*/
@Override
public <T extends SearchEntity> JestResult index(T t, String indexKey) throws JestExcetion{
JestResult jestResult = null;
Index index = new Index
.Builder(t)//文档
.index(indexName)//索引
.type(indexType)//文档类型
.id(indexKey)//key
.build();
try {
jestResult = jestClient.execute(index);
} catch (IOException e) {
LOGGER.info(e.getMessage());
throw new JestExcetion(e.getMessage());
}
return jestResult;
} /**
* 删除索引
* @param id
* @return
* @throws JestExcetion
*/
@Override
public JestResult delete(String id) throws JestExcetion{
JestResult jestResult = null;
Delete delete = new Delete.Builder(id)
.index(indexName)
.type(indexType)
.build();
try {
jestResult = jestClient.execute(delete);
} catch (IOException e) {
LOGGER.info(e.getMessage());
throw new JestExcetion(e.getMessage());
}
return jestResult;
} /**
* 查询索引
* @param id
* @param clazz
* @param <T>
* @return
* @throws JestExcetion
*/
@Override
public <T extends SearchEntity> T get(String id, Class<T> clazz) throws JestExcetion{
JestResult jestResult = null;
Get get = new Get.Builder(indexName, id)
.type(indexType)
.build();
try {
jestResult = jestClient.execute(get);
if (jestResult.isSucceeded()){
return jestResult.getSourceAsObject(clazz);
}
} catch (IOException e) {
LOGGER.info(e.getMessage());
throw new JestExcetion(e.getMessage());
}
return null;
} @Override
public JestResult deleteIndex() throws JestExcetion{
JestResult jestResult = null;
Delete delete = new Delete.Builder(indexName).build();
try {
jestResult = jestClient.execute(delete);
} catch (IOException e) {
LOGGER.info(e.getMessage());
throw new JestExcetion(e.getMessage());
}
return jestResult;
} /**
* 批量新增索引
* @param t
* @param <T>
* @return
* @throws JestExcetion
*/
@Override
public <T extends SearchEntity> JestResult indexBatch(List<T> t) throws JestExcetion {
JestResult jestResult = null;
Bulk.Builder bulk = new Bulk.Builder().defaultIndex(indexName).defaultType(indexType);
for (T obj : t) {
Index index = new Index.Builder(obj).build();
bulk.addAction(index);
}
try {
jestResult = jestClient.execute(bulk.build());
} catch (IOException e) {
LOGGER.info(e.getMessage());
throw new JestExcetion(e.getMessage());
}
return jestResult;
} /**
* 分页查询索引
* @param from 第一页
* @param size 每页几条
* @param queryBuilder 查询条件
* @param clazz
* @param <T>
* @return
* @throws JestExcetion
*/
@Override
public <T extends SearchEntity> List<T> pageSearch(int from, int size, QueryBuilder queryBuilder, Class<T> clazz) throws JestExcetion { List<T> books = null; SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.from(from);
searchSourceBuilder.size(size);
searchSourceBuilder.query(queryBuilder); Search search = new Search.Builder(searchSourceBuilder.toString())
.addIndex(indexName)
.addType(indexType)
.build();
try {
JestResult jestResult = jestClient.execute(search);
if (jestResult.isSucceeded()){
books = jestResult.getSourceAsObjectList(clazz);
}
} catch (IOException e) {
LOGGER.info(e.getMessage());
throw new JestExcetion(e.getMessage());
}
return books;
} @Override
public <T extends SearchEntity> List<T> search(QueryBuilder queryBuilder, Class<T> clazz) throws JestExcetion { List<T> books = null; SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(queryBuilder); Search search = new Search.Builder(searchSourceBuilder.toString())
.addIndex(indexName)
.addType(indexType)
.build(); try {
JestResult jestResult = jestClient.execute(search);
if (jestResult.isSucceeded()){
books = jestResult.getSourceAsObjectList(clazz);
}
} catch (IOException e) {
LOGGER.info(e.getMessage());
throw new JestExcetion(e.getMessage());
}
return books;
} @Override
public Double count(QueryBuilder queryBuilder) throws JestExcetion { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(queryBuilder); Count count = new Count.Builder()
.addIndex(indexName)
.addType(indexType)
.query(searchSourceBuilder.toString())
.build();
try {
CountResult results = jestClient.execute(count);
return results.getCount();
} catch (IOException e) {
LOGGER.info(e.getMessage());
throw new JestExcetion(e.getMessage());
}
} }

JestClientServiceImpl.java

  • junt
package com.huarui.youxiu326;

import com.huarui.entity.Book;
import com.huarui.exection.JestExcetion;
import com.huarui.service.JestClientService;
import com.huarui.service.impl.JestClientServiceImpl;
import io.searchbox.client.JestResult;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List; @RunWith(SpringRunner.class)
@SpringBootTest
public class ComplexSearchTest { private static Logger LOGGER = LoggerFactory.getLogger(ComplexSearchTest.class); @Autowired
private JestClientService jestService; /**
* 批量创建索引
* @throws JestExcetion
*/
@Test
public void testIndexBatch() throws JestExcetion { List<Book> books = new ArrayList<>();
for (int i=327;i<=337;i++){
Book book = new Book(i+"",new Date(),"youxiu"+i,"创建一个索引"+i,3.26F);
books.add(book);
}
JestResult jestResult = jestService.indexBatch(books);
if (jestResult.isSucceeded()){
LOGGER.info("创建成功");
}else{
LOGGER.info("创建失败");
} } /**
* Term 精准查询 并分页
* @throws JestExcetion
*/
@Test
public void testPageSearchUseTerm() throws JestExcetion {
int from = 0;
int size = 2;
//精确搜索
//TermQueryBuilder age = QueryBuilders.termQuery("code", "youxiu326");
//一次匹配多个值
TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("code", Arrays.asList("youxiu326", "youxiu327", "youxiu328", "youxiu329", "youxiu330", "youxiu331"));
//匹配多个字段
QueryBuilders.multiMatchQuery("匹配值","name","code"); List<Book> books = jestService.pageSearch(from, size, termsQueryBuilder, Book.class);
if (books!=null && books.size()>0){
books.stream().forEach(it-> System.out.println(it));
}else{
LOGGER.info("未查询到匹配的数据");
} } /**
* Wildcard 通配符查询 并分页 (支持 *,避免* 开始避免检索大量内容造成效率缓慢)
* @throws JestExcetion
*/
@Test
public void testPageSearchUseWildcard() throws JestExcetion {
int from = 0;
int size = 2; WildcardQueryBuilder wildcardQueryBuilder = QueryBuilders.wildcardQuery("code", "youxiu*"); List<Book> books = jestService.pageSearch(from, size, wildcardQueryBuilder, Book.class);
if (books!=null && books.size()>0){
books.stream().forEach(it-> System.out.println(it));
}else{
LOGGER.info("未查询到匹配的数据");
}
} /**
* 区间搜索
* @throws JestExcetion
*/
@Test
public void testPageSearchUseRange() throws JestExcetion { RangeQueryBuilder RangeQueryBuilder = QueryBuilders.rangeQuery("price")
.from(0.9F)
.to(3.26F)
.includeLower(true) // 包含上界
.includeUpper(true); // 包含下界 List<Book> books = jestService.search(RangeQueryBuilder, Book.class);
if (books!=null && books.size()>0){
books.stream().forEach(it-> System.out.println(it));
}else{
LOGGER.info("未查询到匹配的数据");
}
} /**
* 组合查询
* must(QueryBuilders) : AND
* mustNot(QueryBuilders) : NOT
* should: : OR
* @throws JestExcetion
*/
@Test
public void testPageSearchUseBool() throws JestExcetion {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("code", "youxiu336"))
.mustNot(QueryBuilders.termQuery("name", "创建一个索引332"))
.should(QueryBuilders.termQuery("name", "创建一个索引337")); List<Book> books = jestService.search(boolQueryBuilder,Book.class);
if (books!=null && books.size()>0){
books.stream().forEach(it-> System.out.println(it));
}else{
LOGGER.info("未查询到匹配的数据");
} } /**
* count查询
* @throws JestExcetion
*/
@Test
public void testCount() throws JestExcetion { WildcardQueryBuilder wildcardQueryBuilder = QueryBuilders.wildcardQuery("code", "youxiu*");
Double count = jestService.count(wildcardQueryBuilder);
System.out.println("查询到"+count+"个"); } }

ElasticSearch-学习笔记04-复杂查询的更多相关文章

  1. MyBatis:学习笔记(3)——关联查询

    MyBatis:学习笔记(3)--关联查询 关联查询 理解联结 SQL最强大的功能之一在于我们可以在数据查询的执行中可以使用联结,来将多个表中的数据作为整体进行筛选. 模拟一个简单的在线商品购物系统, ...

  2. Elasticsearch学习笔记一

    Elasticsearch Elasticsearch(以下简称ES)是一款Java语言开发的基于Lucene的高效全文搜索引擎.它提供了一个分布式多用户能力的基于RESTful web接口的全文搜索 ...

  3. elasticsearch学习笔记——相关插件和使用场景

    logstash-input-jdbc学习 ES(elasticsearch缩写)的一大优点就是开源,插件众多.所以扩展起来非常的方便,这也造成了它的生态系统越来越强大.这种开源分享的思想真是与天朝格 ...

  4. ElasticSearch学习笔记(超详细)

    文章目录 初识ElasticSearch 什么是ElasticSearch ElasticSearch特点 ElasticSearch用途 ElasticSearch底层实现 ElasticSearc ...

  5. Redis:学习笔记-04

    Redis:学习笔记-04 该部分内容,参考了 bilibili 上讲解 Redis 中,观看数最多的课程 Redis最新超详细版教程通俗易懂,来自 UP主 遇见狂神说 10. Redis主从复制 1 ...

  6. ElasticSearch 学习记录之ES查询添加排序字段和使用missing或existing字段查询

    ES添加排序 在默认的情况下,ES 是根据文档的得分score来进行文档额排序的.但是自己可以根据自己的针对一些字段进行排序.就像下面的查询脚本一样.下面的这个查询是根据productid这个值进行排 ...

  7. 机器学习实战(Machine Learning in Action)学习笔记————04.朴素贝叶斯分类(bayes)

    机器学习实战(Machine Learning in Action)学习笔记————04.朴素贝叶斯分类(bayes) 关键字:朴素贝叶斯.python.源码解析作者:米仓山下时间:2018-10-2 ...

  8. mybatis学习笔记(10)-一对一查询

    mybatis学习笔记(10)-一对一查询 标签: mybatis mybatis学习笔记10-一对一查询 resultType实现 resultMap实现 resultType和resultMap实 ...

  9. SaToken学习笔记-04

    SaToken学习笔记-04 如果有问题,请点击:传送门 角色认证 在sa-token中,角色和权限可以独立验证 // 当前账号是否含有指定角色标识, 返回true或false StpUtil.has ...

  10. 031 Spring Data Elasticsearch学习笔记---重点掌握第5节高级查询和第6节聚合部分

    Elasticsearch提供的Java客户端有一些不太方便的地方: 很多地方需要拼接Json字符串,在java中拼接字符串有多恐怖你应该懂的 需要自己把对象序列化为json存储 查询到结果也需要自己 ...

随机推荐

  1. 推荐几款顶级的数据可视化及大数据分析BI工具

    如今,有大量强大的可视化工具可用于表达想法.可视化数据.向客户和全球社区分享重要的分析结果.现在大大小小的企业都可以利用商业智能工具来理解复杂的大数据. 这些解决方案可以收集,分析这些数据并将其转换为 ...

  2. Centos6/7系统基础配置-从零到无

    转至:https://www.cnblogs.com/Pigs-Will-Fly/p/13855300.html 目录 前言 系统配置 文档作用 一.Centos 6.X 系列配置 1.1  主机名 ...

  3. mysql索引技术名词1-5

    目录 索引技术名词 1.回表 2.覆盖索引 3.最左匹配原则 4.索引下推 5.谓词下推 索引技术名词 1.回表 注意: 1.如果依靠主键查询,叶子结点直接存储数据----主键B+树 2.如果依靠其他 ...

  4. 反射、静态代理、动态代理(jdk、cglib)

    一.反射 反射在之前的文章中详细的解释过了,简单概括就是:可以动态的获取到一个类内部的所有的信息,动态的去创建对象和使用对象以及可以操作对象的属性和方法. 二.代理 首先解释一下代理:使用一个代理对象 ...

  5. omnet++:官方文档翻译总结(三)

    翻译总结自:Turning it Into a Real Network - OMNeT++ Technical Articles 接官方文档翻译总结(二),本节主要是真实网络的搭建 Part 4 - ...

  6. JZ-047-求 1+2+3+...+n

    标题 求 1+2+3+...+n 求1+2+3+...+n,要求不能使用乘除法.for.while.if.else.switch.case等关键字及条件判断语句(A?B:C). 题目链接: 求 1+2 ...

  7. CMAK(Kafka Manager)安装

    CMAK 是管理Kafka集群的常用工具,之前的名字叫Kafka Manager.CMAK功能很强大,它可以管理多个Kafka集群,查看集群内部状态,如:topic.broker.consumer.p ...

  8. Node.js躬行记(16)——活动配置化

    一直想将一些常规活动抽象化,制作成可配置的.原先的计划是做成拖拽的,那种可视化搭建,运营也能自己搭建页面. 这是一个美好的愿景,但是现实不允许我花太多精力去制作这样一个系统.经过权衡后,先设计成一个可 ...

  9. think php 7天免登录

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. vue监听页面中的某个div的滚动事件,并判断滚动的位置

    在开发中常常会遇到这样一个vue页面,页面分为左右两部分,左边是目录树,右边是一个类名为xq-box的div,在xq-box中多个div上下并列布局,每个div中的内容就对应着左边目录树中的相应节点, ...