• ElasticSearch-学习笔记04-复杂查询


    • 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+"个");
    
        }
    
    }
    
  • 相关阅读:
    60.django session缓存配置
    Jmeter学习笔记-Jmeter目录文件
    Jmeter用户手册目录
    Jmeter学习笔记-jmeter执行结束报错:The JVM should have exitted but did not
    PPT-分割图片
    bug记录-权限问题,比如说默认搜索条件为子系统,则在该子系统下面的接口模版,在搜索条件下也应该有权限的限制
    bug记录-弹出框,刚配置的时候记录少,当记录过多时,容易出现高度过高,所以要对高度进行限制,以及设置滚动条
    Jmeter学习笔记-20181224安装软件路径及linux安装方法
    bug记录-列表头部缺失,点开页面,列表头部存在,然后点击搜索后,某个枚举没有值,搜出来没有列表头部,换成其他有值的列表头部,列表头部不显示了
    视频录制与剪辑备忘记录
  • 原文地址:https://www.cnblogs.com/youxiu326/p/elasticSearch-complex-search.html
Copyright © 2020-2023  润新知