Fork me on GitHub

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+"个");

    }

}

 

posted @ 2019-04-06 21:20  youxiu326  阅读(344)  评论(0编辑  收藏  举报