ElasticSearch 测试


Java 编程语言,实现es原生TCP连接端口9300测试(http端口9200)

  • pom.xml添加坐标依赖
<?xml version="1.0" encoding="UTF-8"?>

    4.0.0

    com.yuyz
    es-demo
    1.0-SNAPSHOT
    elasticsearch测试工程
    
        
            org.elasticsearch
            elasticsearch
            7.4.0
        
        
            org.elasticsearch.client
            transport
            7.4.0
        
        
            com.alibaba
            fastjson
            1.2.56
        
    

  • 创建索引,配置映射
package com.yuyz.es.index;

import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;

/**
 * @author yuyz
 * @version 1.0
 * @create 2022-02-21
 * @description es创建索引测试
 */
public class Test {

    /**
     * 创建索引及类型、映射
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        //构建客户端,不使用集群
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY);
        //连接es
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));
        //设置建表信息
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject()
                    .startObject("info")
                        .startObject("properties")
                            .startObject("id")
                                .field("type", "text")
                            .endObject()
                            .startObject("title")
                                .field("type", "text")
                                .field("analyzer", "ik_max_word")
                            .endObject()
                            .startObject("content")
                                .field("type", "text")
                            //设置ik分词器有两种:ik_smart,ik_max_word
                                .field("analyzer", "ik_max_word")
                            .endObject()
                        .endObject()
                    .endObject()
                .endObject();
        //构建映射请求对象
        PutMappingRequest source = Requests.putMappingRequest("java0823_article")
                .type("info").source(builder);
        //将映射存储到指定的索引中
        client.admin().indices().putMapping(source).get();
        //关闭连接
        client.close();
    }

    /**
     * 创建索引
     * @param args
     * @throws Exception
     */
    public static void main1(String[] args) throws Exception{
        //初始化连接客户端,Settings.EMPTY表示不使用集群
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY);
        //设置IP地址和端口号,创建连接
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300));
        //创建索引,get()提交事务
        client.admin().indices().prepareCreate("java0823_article").get();
        //删除索引
//        client.admin().indices().prepareDelete("java0823").get();
        //释放连接
        client.close();
    }
}
  • 创建测试实例类pojo
package com.yuyz.es.pojo;

import java.io.Serializable;

/**
 * @author yuyz
 * @version 1.0
 * @create 2022-02-21
 * @description 测试实体类
 */
public class Article implements Serializable {
    private Long id;
    private String title;
    private String content;

    public Article() {
    }

    public Article(Long id, String title, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    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;
    }

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}
  • 新增数据document
import java.net.InetAddress;

/**
 * @author yuyz
 * @version 1.0
 * @create 2022-02-21
 * @description es新增数据
 */
public class Create {

    /**
     * 批量新增数据
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY);
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));

        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();

        for (long i = 0L; i < 100L; i++) {
            Article article = new Article();
            article.setId(i);
            article.setTitle("Elasticsearch是一个基于Lucene的搜索服务器。" + i);
            article.setContent("它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。" +
                    "Elasticsearch是用Java语言开发的,并作为Apache许可条款下的开放源码发布,是一种流行的企业级搜索引擎。" +
                    "Elasticsearch用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。" +
                    "官方客户端在Java、.NET(C#)、PHP、Python、Apache Groovy、Ruby和许多其他语言中都是可用的。" +
                    "根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr,也是基于Lucene。");
            bulkRequestBuilder.add(client.prepareIndex("java0823_article", "info", i + "")
                    //保存数据方式
                    .setSource(JSONObject.toJSONString(article), XContentType.JSON));
            //分批提交
            if(i%100==0){
                bulkRequestBuilder.get();
            }
        }
        client.close();
    }


    /**
     * 新增一条数据
     *
     * @param args
     * @throws Exception
     */
    public static void main1(String[] args) throws Exception {
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY);
        //创建连接
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));

        //需要保存到es的数据
        Article article = new Article();
        article.setId(1001L);
        article.setTitle("Elasticsearch是一个基于Lucene的搜索服务器。");
        article.setContent("它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。" +
                "Elasticsearch是用Java语言开发的,并作为Apache许可条款下的开放源码发布,是一种流行的企业级搜索引擎。" +
                "Elasticsearch用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。" +
                "官方客户端在Java、.NET(C#)、PHP、Python、Apache Groovy、Ruby和许多其他语言中都是可用的。" +
                "根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr,也是基于Lucene。");
        //指定索引和表
        client.prepareIndex("java0823_article", "info", "1")
                //保存数据方式
                .setSource(JSONObject.toJSONString(article), XContentType.JSON).get();
        //关闭连接
        client.close();
    }
}
  • es查询测试
package com.yuyz.es.search;

import com.alibaba.fastjson.JSONObject;
import com.yuyz.es.pojo.Article;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.util.Iterator;

/**
 * @author yuyz
 * @version 1.0
 * @create 2022-02-21
 * @description es查询数据
 */
public class Search {
    /**
     * 根据文档下标id查询单数据,单次查询
     * @param args
     * @throws Exception
     */
    public static void main1(String[] args) throws Exception{
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY);
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300));
        GetResponse getResponse = client.prepareGet("java0823_article", "info", "18").get();
        String sourceAsString = getResponse.getSourceAsString();
        System.out.println("sourceAsString = " + sourceAsString);
        client.close();
    }

    /**
     * 字符串查询:对输入的条件进行分词,查询2次:索引域 文档域
     * 默认查询显示10条数据(不做分页查询处理)
     *
     * 词条查询:把条件认为是一个词语。对查询条件不会分词,查询2次
     *
     * 模糊查询:不会对模糊查询条件进行分词处理
     *
     * 相似度查询:对输入的条件也不分词
     *
     * 范围查询:
     *
     * 组合查询:多条件查询 must shout mustno
     *
     * 排序分页查询:
     * @param args
     */
    public static void main2(String[] args) throws Exception{

        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY);
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300));

        //设置高亮查询域
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("content");
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");
        SearchResponse searchResponse = client.prepareSearch("java0823_article")//索引
                .setTypes("info")//类型
//                .setQuery(QueryBuilders.matchAllQuery())//查询条件:查询所有
//                .setQuery(QueryBuilders.queryStringQuery("搜索").field("content"))//查询条件:字符串查询
//                .setQuery(QueryBuilders.termQuery("content","搜索"))//查询条件:词条查询
//                .setQuery(QueryBuilders.wildcardQuery("content","搜索*"))//查询条件:模糊查询
//                .setQuery(QueryBuilders.fuzzyQuery("content","ElasticSearch"))//查询条件:相似度查询
//                .setQuery(QueryBuilders.rangeQuery("id").gt(10).lt(20))//查询条件:范围查询
//                .setQuery(QueryBuilders.boolQuery()//查询条件:组合查询
//                        .must(QueryBuilders.rangeQuery("id").gt(10).lt(20))
//                        .should(QueryBuilders.fuzzyQuery("content","ElasticSearch"))
//                )
                .setQuery(QueryBuilders.matchAllQuery())//查询条件:排序分页查询
                .setFrom(0)//第几条开始
                .setSize(100)//共查询几条数据
                .addSort("id", SortOrder.DESC)//根据id域降序
                .highlighter(highlightBuilder)//设置高亮查询
                .get();//执行查询
        SearchHits hits = searchResponse.getHits();//获取查询结果
        Iterator iterator = hits.iterator();//获取迭代器
        while (iterator.hasNext()){//遍历
            SearchHit next = iterator.next();
            //获取高亮查询结果
            HighlightField highlightField = next.getHighlightFields().get("content");
            String sourceAsString = next.getSourceAsString();
            //反序列化
            Article article = JSONObject.parseObject(sourceAsString, Article.class);
            //验空
            if(highlightBuilder != null){
                //获取高亮数据的数组
                Text[] fragments = highlightField.getFragments();
                String text = "";
                //数据拼接
                for (Text fragment : fragments) {
                    text += fragment;
                }
                article.setContent(text);
            }
            //打印结果
            System.out.println(article.toString());
        }
    }
}