ElasticSearch测试小例子

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qian_348840260/article/details/12708151


1.配置类

package com.es.config;

public class AppConstansts {

   public static final String index = "news";
   public static final String type = "article";
   public static final String pwd = "123456";

}

package com.es.config;

import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.ClientConfig;

public class InitEsConfig {
    
    public static JestClient jestClient(){
        ClientConfig clientConfig = new ClientConfig.Builder("http://localhost:9200").multiThreaded(true).build();
        JestClientFactory factory = new JestClientFactory();
        factory.setClientConfig(clientConfig);
        JestClient client = factory.getObject();
        return client;
    }

}

2.POJO

package com.es.model;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.builder.ToStringBuilder;

public class News {

    private long id = 0;
    private int cityId =0;
    private String title = "";
    private String content = "";
    
    private long avgPrice = 0;
    private long lowPrice = 0;
    private long maxPrice = 0;
    
    private List<String> projTypeList = new ArrayList<String>();
    private List<Long> saleDateList = new ArrayList<Long>();
    private String discount = "";
    
    public News id(long id){
        this.id = id;
        return this;
    }
    
    public News cityId(int cityId){
        this.cityId = cityId;
        return this;
    }
    
    public News title(String title){
        this.title = title;
        return this;
    }
    
    public News content(String content){
        this.content = content;
        return this;
    }
    
    public News avgPrice(long avgPrice){
        this.avgPrice = avgPrice;
        return this;
    }
    
    public News lowPrice(long lowPrice){
        this.lowPrice = lowPrice;
        return this;
    }
    
    public News maxPrice(long maxPrice){
        this.maxPrice = maxPrice;
        return this;
    }
    
    public News discount(String discount){
        this.discount = discount;
        return this;
    }
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public int getCityId() {
        return cityId;
    }
    public void setCityId(int cityId) {
        this.cityId = cityId;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public long getAvgPrice() {
        return avgPrice;
    }
    public void setAvgPrice(long avgPrice) {
        this.avgPrice = avgPrice;
    }
    public long getLowPrice() {
        return lowPrice;
    }
    public void setLowPrice(long lowPrice) {
        this.lowPrice = lowPrice;
    }
    public long getMaxPrice() {
        return maxPrice;
    }
    public void setMaxPrice(long maxPrice) {
        this.maxPrice = maxPrice;
    }
    public List<String> getProjTypeList() {
        return projTypeList;
    }
    public void setProjTypeList(List<String> projTypeList) {
        this.projTypeList = projTypeList;
    }
    public String getDiscount() {
        return discount;
    }
    public void setDiscount(String discount) {
        this.discount = discount;
    }
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    public List<Long> getSaleDateList() {
        return saleDateList;
    }

    public void setSaleDateList(List<Long> saleDateList) {
        this.saleDateList = saleDateList;
    }
    
    public News projTypeList(String... type){
        for(String temp:type)
            projTypeList.add(temp);
        return this;
    }
    
    public News saleDateList(Long... sal){
        for(Long temp:sal)
            saleDateList.add(temp);
        return this;
    }
    
    public News addThisToList(List<News> list){
        list.add(this);
        return this;
    }

}

3.删除索引

package com.es.delete;

import com.es.config.InitEsConfig;

import io.searchbox.indices.DeleteIndex;

public class EsDeleteIndex {

    public static void deleteIndex(String index){
        try{
            DeleteIndex deleteIndex = new DeleteIndex(new DeleteIndex.Builder(index));
            InitEsConfig.jestClient().execute(deleteIndex);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}

4.创建索引

package com.es.index;

import java.util.List;

import io.searchbox.client.JestClient;
import io.searchbox.core.Bulk;
import io.searchbox.core.Index;
import io.searchbox.indices.CreateIndex;

import com.es.config.InitEsConfig;
import com.es.model.News;

public class EsCreateIndex {

    public static void createIndex(List<News> newsList,String index,String type) {
        try{
            JestClient jestClient = InitEsConfig.jestClient();
            CreateIndex createIndex = new CreateIndex(new CreateIndex.Builder("news"));
            jestClient.execute(createIndex);
            
            Bulk.Builder builder = new Bulk.Builder().defaultIndex("news").defaultType("article");
            //引发的血案
            builder.refresh(true);
            for (News news:newsList) {
                builder.addAction(new Index.Builder(news).build());
            }
            Bulk bulk = new Bulk(builder);
            jestClient.execute(bulk);
        }catch(Exception e){
            e.printStackTrace();
        }
/*        try {
            for (News news : newsList) {
                Index.Builder builder = new Index.Builder(news);
                // 创建索引库 需要注意的是.setRefresh(true)这里一定要设置,否则第一次建立索引查找不到数据
                builder.refresh(true);
                Index index1 = builder.index("news").type("article").build();
                InitEsConfig.jestClient().execute(index1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/


    }

}

5.搜索索引

package com.es.search;

import java.util.List;

import org.apache.commons.lang.builder.ToStringBuilder;

import com.es.config.AppConstansts;
import com.es.config.InitEsConfig;
import com.es.delete.EsDeleteIndex;
import com.es.esquery.EsQuery;
import com.es.index.EsCreateIndex;
import com.es.model.News;

import io.searchbox.client.JestResult;
import io.searchbox.core.Search;

public class SearchService {


    public static List<News> searchService(EsQuery query) throws Exception {
        //删除索引
        EsDeleteIndex.deleteIndex(AppConstansts.index);
        //创建索引
        EsCreateIndex.createIndex(query.prepareData(),AppConstansts.index,AppConstansts.type);
        
        Search.Builder builder = new Search.Builder("{\"query\":" + query.buildQuery().toString() + "}");
        System.out.println("{\"query\":" + query.buildQuery().toString() + "}");
        builder.addIndex(AppConstansts.index)
        .addType(AppConstansts.type)
//        .setHeader("X-SCE-ES-PASSWORD", AppConstansts.pwd)
        .setParameter("from", query.getFrom())
        .setParameter("size", query.getSize())
        ;
        if(query.getSort()!=null){
            builder.addSort(query.getSort());
        }
        JestResult result = InitEsConfig.jestClient().execute(builder.build());
//      System.out.println(result.getJsonObject());
        System.out.println("命中数:" + result.getJsonObject().get("hits").getAsJsonObject().get("total").getAsInt());
        return InitEsConfig.jestClient().execute(builder.build()).getSourceAsObjectList(News.class);
    }

}

6.测试用例

package com.es.esquery;

import java.util.List;

import io.searchbox.core.search.sort.Sort;

import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.QueryBuilder;

public interface EsQuery {
    /**
     * 组建es query
     * @return
     */
    QueryBuilder buildQuery();
    /**
     * 组建es filter
     * @return
     */
    FilterBuilder buildFilter();
    /**
     * 获取搜索结果的from
     * @return
     */
    int getFrom();
    /**
     * 获取搜索结果的size
     * @return
     */
    int getSize();
    /**
     * 获取排序方式
     * @return
     */
    Sort getSort();
    /**
     * 获取ES 检索结果的类型
     * @return
     */
    <T> Class<T> getResultClass();
    
    List<com.es.model.News> prepareData();
}

package com.es.esquery;

import io.searchbox.core.search.sort.Sort;

import org.elasticsearch.index.query.BoolFilterBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilteredQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;


public abstract class AbstractEsQuery implements EsQuery {

    Integer pageIndex = 0;
    Integer pageSize = 10;
  
  public QueryBuilder composeQuery(BoolQueryBuilder query, FilterBuilder filter) {
      if(filter == null) return query;
      query = (query == null ? new BoolQueryBuilder().must(QueryBuilders.matchAllQuery()) : query);
      return new FilteredQueryBuilder(query, filter);
  }

  public BoolFilterBuilder mustFilter(BoolFilterBuilder boolFilter, FilterBuilder filter) {
      boolFilter = (boolFilter == null ? new BoolFilterBuilder() : boolFilter);
      boolFilter.must(filter);
      return boolFilter;
  }

/*  public BoolQueryBuilder mustQuery(BoolQueryBuilder boolQuery, QueryBuilder query) {
      boolQuery = (boolQuery == null ? new BoolQueryBuilder() : boolQuery);
      boolQuery.must(query);
      return boolQuery;
  }*/
  
  public BoolQueryBuilder mustQuery(BoolQueryBuilder boolQuery, QueryBuilder... querys) {
      boolQuery = (boolQuery == null ? new BoolQueryBuilder() : boolQuery);
      for(QueryBuilder query:querys){
          boolQuery.must(query);
      }
      return boolQuery;
  }
  
  public int getFrom(){
      return pageIndex*pageSize;
  }

  public int getSize(){
      return pageSize;
  }

  public Integer getPageIndex() {
      return pageIndex;
  }

  public Integer getPageSize() {
      return pageSize;
  }
  
  @Override
  public Sort getSort() {
      return null;
  }

  @Override
  public <T> Class<T> getResultClass() {
      return null;
  }
}

package com.es.esquery.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilder;


import com.es.esquery.AbstractEsQuery;
import com.es.model.News;
/**
 * 过滤掉字符串为""的 document
 * @author liangliangqian
 *
 */
public class TestEmptyString extends AbstractEsQuery{

    @Override
    public QueryBuilder buildQuery() {
        return composeQuery(null,buildFilter());
//      return QueryBuilders.regexpQuery("title", "[\\s\\S]");
//        return QueryBuilders.matchPhraseQuery("title", " ");
//        return QueryBuilders.matchAllQuery();
    }

    @Override
    public FilterBuilder buildFilter() {
        return FilterBuilders.regexpFilter("title", ".+");
    }



    @Override
    public List<News> prepareData() {
        List<News> list = new ArrayList<News>();
        News news1 = new News().id(1).title("检验").content("1");
        News news2 = new News().id(1).title("tttt").content("1");
        News news3 = new News().id(1).content("1");
        list.add(news1);
        list.add(news2);
        list.add(news3);
        return list;
    }

    public static void main(String[] args){
        
        String name = "";
        
        Pattern pattern = Pattern.compile(".+");
        Matcher matcher = pattern.matcher(name);
        System.out.println(matcher.find());
    }

}

package com.es.esquery.impl;

import java.util.ArrayList;
import java.util.List;

import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilder;

import com.es.esquery.AbstractEsQuery;
import com.es.model.News;

public class TestLongArray extends AbstractEsQuery {

    @Override
    public QueryBuilder buildQuery() {
        return composeQuery(null,buildFilter());
    }

    @Override
    public FilterBuilder buildFilter() {
        //saleDateList数组中的某个值必须在500-600之间
        return FilterBuilders.rangeFilter("saleDateList")
                .from(500)
                .to(600)
                .includeLower(false)
                .includeUpper(false);
    }

    @Override
    public List<News> prepareData() {
        List<News> list = new ArrayList<News>();
        News news1 = new News().id(1).title("检验").content("1").avgPrice(10).saleDateList(1000l).saleDateList(2000l);
        News news2 = new News().id(2).title("tttt").content("1").lowPrice(5).maxPrice(78).saleDateList(550l).saleDateList(4000l);
        News news3 = new News().id(3).content("1");
        list.add(news1);
        list.add(news2);
        list.add(news3);
        return list;
    }

}

package com.es.esquery.impl;

import java.util.ArrayList;
import java.util.List;

import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import com.es.esquery.AbstractEsQuery;
import com.es.model.News;
/**
 * 过滤到avgPrice lowPrice maxPrice全为0的情况
 * @author liangliangqian
 *
 */
public class TestMultiLong extends AbstractEsQuery{

    @Override
    public QueryBuilder buildQuery() {
//        return QueryBuilders.matchPhraseQuery("avgPrice", 10);//.fieldQuery("avgPrice", 10);//.termQuery("avgPrice", 10);
        return composeQuery(null,buildFilter());
    }

    @Override
    public FilterBuilder buildFilter() {
        return FilterBuilders.notFilter(FilterBuilders.queryFilter(mustQuery(null,new QueryBuilder[]{
                QueryBuilders.matchPhraseQuery("avgPrice", 0),
                QueryBuilders.fieldQuery("lowPrice", 0),
                QueryBuilders.termQuery("maxPrice", 0)})));
    }

    @Override
    public List<News> prepareData() {
        List<News> list = new ArrayList<News>();
        News news1 = new News().id(1).title("检验").content("1").avgPrice(10);
        news1.getProjTypeList().add("1");
        news1.getProjTypeList().add("4");
        news1.getProjTypeList().add("7");
        News news2 = new News().id(1).title("tttt").content("1").lowPrice(5).maxPrice(78);
        News news3 = new News().id(1).content("1");
        list.add(news1);
        list.add(news2);
        list.add(news3);
        return list;
    }


}

package com.es.esquery.impl;

import java.util.ArrayList;
import java.util.List;

import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import com.es.esquery.AbstractEsQuery;
import com.es.model.News;

public class TestStrArray extends AbstractEsQuery{

    @Override
    public QueryBuilder buildQuery() {
        return composeQuery(null,buildFilter());
    }

    @Override
    public FilterBuilder buildFilter() {
        //projTypeList里面包含1或2的 id=1,4,6
//        return FilterBuilders.inFilter("projTypeList", "1","2");
        //projTypeList里面不包含1,2当中的任意
        return FilterBuilders.notFilter(FilterBuilders.inFilter("projTypeList", new String[]{"1","2"}));
    }

    @Override
    public List<News> prepareData() {
        List<News> list = new ArrayList<News>();
        new News().id(1).addThisToList(list).title("检验").content("1").avgPrice(10).saleDateList(1000l,2000l)
                    .projTypeList("1","2","5","9");
        new News().id(2).addThisToList(list).title("tttt").content("1").lowPrice(5).maxPrice(78).saleDateList(550l,4000l)
                    .projTypeList("3","15");
        new News().id(3).addThisToList(list).content("1");
        new News().id(4).addThisToList(list)
                    .projTypeList("1","9");
        new News().id(5).addThisToList(list)
                    .projTypeList("3");
        new News().id(6).addThisToList(list)
                    .projTypeList("1","2","3");
        return list;
    }

    

}

7.Main类

import java.util.List;

import com.es.esquery.EsQuery;
import com.es.esquery.impl.TestStrArray;
import com.es.search.SearchService;


public class Main {

    public static void main(String[] args) throws Exception {
        EsQuery query = new TestStrArray();
        List<com.es.model.News> newsList = SearchService.searchService(query);
        for(com.es.model.News news:newsList){
            System.out.println(news);
        }
        
    }

}


展开阅读全文

没有更多推荐了,返回首页