Java原生操作Elasticsearch

本文涉及的产品
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
简介: Java原生操作Elasticsearch

【1】获取PreBuiltTransportClient

实例代码

  @Test
    public void getClient() throws Exception {
        Settings settings= Settings.builder().put("cluster.name","my-application").build();
        PreBuiltTransportClient client = new PreBuiltTransportClient(settings);
        byte[] addr = {(byte) 192, (byte) 168,18, (byte) 128};
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByAddress(addr),9300));
        System.out.println(client);
    }

控制台打印

 io.netty.channel.DefaultChannelId - -Dio.netty.machineId: 28:d2:44:ff:fe:f0:2f:30 (auto-detected)
 io.netty.util.internal.InternalThreadLocalMap - -Dio.netty.threadLocalMap.stringBuilder.initialSize: 1024
 io.netty.util.internal.InternalThreadLocalMap - -Dio.netty.threadLocalMap.stringBuilder.maxSize: 4096
 io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.level: simple
 io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.targetRecords: 4
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.numHeapArenas: 8
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.numDirectArenas: 8
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.pageSize: 8192
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxOrder: 11
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.chunkSize: 16777216
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.tinyCacheSize: 512
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.smallCacheSize: 256
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.normalCacheSize: 64
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxCachedBufferCapacity: 32768
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.cacheTrimInterval: 8192
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.useCacheForAllThreads: true
 io.netty.buffer.ByteBufUtil - -Dio.netty.allocator.type: pooled
 io.netty.buffer.ByteBufUtil - -Dio.netty.threadLocalDirectBufferSize: 0
 io.netty.buffer.ByteBufUtil - -Dio.netty.maxThreadLocalCharBufferSize: 16384
 io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.bytebuf.checkAccessible: true
 io.netty.util.ResourceLeakDetectorFactory - Loaded default ResourceLeakDetector: io.netty.util.ResourceLeakDetector@5f5b5ca4
 io.netty.util.Recycler - -Dio.netty.recycler.maxCapacityPerThread: 4096
 io.netty.util.Recycler - -Dio.netty.recycler.maxSharedCapacityFactor: 2
 io.netty.util.Recycler - -Dio.netty.recycler.linkCapacity: 16
 io.netty.util.Recycler - -Dio.netty.recycler.ratio: 8
 org.elasticsearch.transport.netty4.Netty4Transport - connected to node [{#transport#-1}{DX4Qcrb4QAaGAgDUb-XYxg}{192.168.18.128}{192.168.18.128:9300}]
 org.elasticsearch.transport.netty4.Netty4Transport - connected to node [{node-1}{rBJNxRw2RxisNp-uBs8o4g}{10h3v06bR4SI4x4ee0F1HQ}{192.168.18.128}{192.168.18.128:9300}]
org.elasticsearch.transport.client.PreBuiltTransportClient@7af1cd63


【2】创建索引

实例代码:

  @Test
    public void createIndex(){
        CreateIndexResponse blog = client.admin().indices().prepareCreate("my-blog").get();
        System.out.println(blog);
        client.close();
    }

控制台打印

查看当前ES中索引

http://192.168.18.128:9200/_cat/indices

查看my-blog详细

http://192.168.18.128:9200/my-blog?pretty

如果不加pretty参数则如下所示:

Elasticsearch索引结束时将得到5个分片及其各自1个副本。简单来说,操作结束时,将有10个Lucene索引分布在集群中。


【3】删除索引

实例代码

  @Test
    public void deleteIndex(){
        // 1 删除索引
        DeleteIndexResponse deleteIndexResponse = client.admin().indices().prepareDelete("my-blog").get();
        System.out.println(deleteIndexResponse);
        // 2 关闭连接
        client.close();
    }

控制台打印

查询索引确认索引已经删除


【4】创建文档

① 以json串方式新建文档


当直接在ElasticSearch建立文档对象时,如果索引不存在的,默认会自动创建,映射采用默认方式。

实例代码:

  @Test
    public void createIndexByJson() {
        // 1 文档数据准备
        String json = "{" + "\"id\":\"1\"," + "\"title\":\"基于Lucene的搜索服务器\","
                + "\"content\":\"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"" + "}";
        // 2 创建文档
        IndexResponse indexResponse = client.prepareIndex("my-blog", "article", "1").setSource(json).execute().actionGet();
        // 3 打印返回的结果
        System.out.println("index:" + indexResponse.getIndex());
        System.out.println("type:" + indexResponse.getType());
        System.out.println("id:" + indexResponse.getId());
        System.out.println("version:" + indexResponse.getVersion());
        System.out.println("result:" + indexResponse.getResult());
        // 4 关闭连接
        client.close();
    }


控制台打印:

浏览器查看http://192.168.18.128:9200/my-blog?pretty


② 源数据map方式添加json创建文档

实例代码:

   @Test
    public void createIndexByMap() {
        // 1 文档数据准备
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("id", "2");
        json.put("title", "基于Lucene的搜索服务器");
        json.put("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");
        // 2 创建文档
        IndexResponse indexResponse = client.prepareIndex("my-blog", "article", "2").setSource(json).execute().actionGet();
        // 3 打印返回的结果
        System.out.println("index:" + indexResponse.getIndex());
        System.out.println("type:" + indexResponse.getType());
        System.out.println("id:" + indexResponse.getId());
        System.out.println("version:" + indexResponse.getVersion());
        System.out.println("result:" + indexResponse.getResult());
        // 4 关闭连接
        client.close();
    }

控制台打印:

浏览器确认该索引文档http://192.168.18.128:9200/my-blog/_search?pretty

浏览器查询ES所有信息http://192.168.18.128:9200/_all/_search?pretty

③ 源数据es构建器添加json创建文档

实例代码:

  @Test
  public void createIndex() throws Exception {
    // 1 通过es自带的帮助类,构建json数据
    XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("id", 3)
        .field("title", "基于Lucene的搜索服务器").field("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。")
        .endObject();
    // 2 创建文档
    IndexResponse indexResponse = client.prepareIndex("my-blog", "article", "3").setSource(builder).get();
    // 3 打印返回的结果
    System.out.println("index:" + indexResponse.getIndex());
    System.out.println("type:" + indexResponse.getType());
    System.out.println("id:" + indexResponse.getId());
    System.out.println("version:" + indexResponse.getVersion());
    System.out.println("result:" + indexResponse.getResult());
    // 4 关闭连接
    client.close();
  }


控制台打印:

浏览器查询确认http://192.168.18.128:9200/my-blog/_search?pretty

【5】查询索引中文档数据

① 根据索引ID查询单条数据

实例代码:

   @Test
    public void getData() throws Exception {
        // 1 查询文档
        GetResponse response = client.prepareGet("my-blog", "article", "1").get();
        // 2 打印搜索的结果
        System.out.println(response.getSourceAsString());
        // 3 关闭连接
        client.close();
    }

控制台打印:


② 根据索引ID查询多条数据

实例代码:

   @Test
    public void getMultiData() {
        // 1 查询多个文档
        MultiGetResponse response = client.prepareMultiGet().add("my-blog", "article", "1").add("my-blog", "article", "2", "3")
                .add("my-blog", "article", "2").get();
        // 2 遍历返回的结果
        for(MultiGetItemResponse itemResponse:response){
            GetResponse getResponse = itemResponse.getResponse();
            // 如果获取到查询结果
            if (getResponse.isExists()) {
                String sourceAsString = getResponse.getSourceAsString();
                System.out.println(sourceAsString);
            }
        }
        // 3 关闭资源
        client.close();
    }

控制台打印:


【6】更新索引文档数据

① update-更新文档数据

实例代码:

  @Test
    public void updateData() throws Throwable {
        // 1 创建更新数据的请求对象
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index("my-blog");
        updateRequest.type("article");
        updateRequest.id("3");
        updateRequest.doc(XContentFactory.jsonBuilder().startObject()
                // 对没有的字段添加, 对已有的字段替换
                .field("title", "基于Lucene的搜索服务器")
                .field("content",
                        "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。大数据前景无限")
                .field("createDate", "2019-12-22").endObject());
        // 2 获取更新后的值
        UpdateResponse indexResponse = client.update(updateRequest).get();
        // 3 打印返回的结果
        System.out.println("index:" + indexResponse.getIndex());
        System.out.println("type:" + indexResponse.getType());
        System.out.println("id:" + indexResponse.getId());
        System.out.println("version:" + indexResponse.getVersion());
        System.out.println("create:" + indexResponse.getResult());
        // 4 关闭连接
        client.close();
    }

控制台打印:

浏览器查询确认http://192.168.18.128:9200/my-blog/_search?pretty


② upsert-更新文档数据


设置查询条件, 查找不到则添加IndexRequest内容,查找到则按照UpdateRequest更新。

实例代码:

    @Test
    public void testUpsert() throws Exception {
        // 设置查询条件, 查找不到则添加
        IndexRequest indexRequest = new IndexRequest("my-blog", "article", "5")
                .source(XContentFactory.jsonBuilder().startObject().field("title", "搜索服务器").field("content","它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。").endObject());
        // 设置更新, 查找到更新下面的设置
        UpdateRequest upsert = new UpdateRequest("my-blog", "article", "5")
                .doc(XContentFactory.jsonBuilder().startObject().field("user", "李四").endObject()).upsert(indexRequest);
        client.update(upsert).get();
        client.close();
    }

浏览器查询确认http://192.168.18.128:9200/my-blog/_search?pretty


【7】删除文档数据

实例代码:

  @Test
  public void deleteData() {
    // 1 删除文档数据
    DeleteResponse indexResponse = client.prepareDelete("blog", "article", "5").get();
    // 2 打印返回的结果
    System.out.println("index:" + indexResponse.getIndex());
    System.out.println("type:" + indexResponse.getType());
    System.out.println("id:" + indexResponse.getId());
    System.out.println("version:" + indexResponse.getVersion());
    System.out.println("found:" + indexResponse.getResult());
    // 3 关闭连接
    client.close();
  }

控制台打印:

浏览器查询确认http://192.168.18.128:9200/my-blog/_search?pretty


【8】条件查询

① 查询索引所有文档数据(matchAllQuery)

实例代码:

  @Test
    public void matchAllQuery() {
        // 1 执行查询
        SearchResponse searchResponse = client.prepareSearch("my-blog").setTypes("article")
                .setQuery(QueryBuilders.matchAllQuery()).get();
        // 2 打印查询结果
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象
        System.out.println("查询结果有:" + hits.getTotalHits() + "条");
        Iterator<SearchHit> iterator = hits.iterator();
        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next(); // 每个查询对象
            System.out.println(searchHit.getSourceAsString()); // 获取字符串格式打印
        }
        // 3 关闭连接
        client.close();
    }

控制台打印:


② 对所有字段分词查询(queryStringQuery)

实例代码:

  @Test
    public void query() {
        // 1 条件查询
        SearchResponse searchResponse = client.prepareSearch("my-blog").setTypes("article")
                .setQuery(QueryBuilders.queryStringQuery("全文")).get();
        // 2 打印查询结果
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象
        System.out.println("查询结果有:" + hits.getTotalHits() + "条");
        Iterator<SearchHit> iterator = hits.iterator();
        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next(); // 每个查询对象
            System.out.println(searchHit.getSourceAsString()); // 获取字符串格式打印
        }
        // 3 关闭连接
        client.close();
    }

控制台打印:


③ 通配符查询(wildcardQuery)

*:表示多个字符(任意的字符)
?:表示单个字符

实例代码:

   @Test
    public void wildcardQuery() {
        // 1 通配符查询
        SearchResponse searchResponse = client.prepareSearch("my-blog").setTypes("article")
                .setQuery(QueryBuilders.wildcardQuery("content", "*全*")).get();
        // 2 打印查询结果
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象
        System.out.println("查询结果有:" + hits.getTotalHits() + "条");
        Iterator<SearchHit> iterator = hits.iterator();
        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next(); // 每个查询对象
            System.out.println(searchHit.getSourceAsString()); // 获取字符串格式打印
        }
        // 3 关闭连接
        client.close();
    }

控制台打印:


④ 词条查询(TermQuery)

实例代码;

  @Test
    public void termQuery() {
        // 1 第一field查询
//        SearchResponse searchResponse = client.prepareSearch("my-blog").setTypes("article")
//                .setQuery(QueryBuilders.termQuery("content", "全文")).get();//0条
        SearchResponse searchResponse = client.prepareSearch("my-blog").setTypes("article")
                .setQuery(QueryBuilders.termQuery("content", "全")).get();//3条
        // 2 打印查询结果
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象
        System.out.println("查询结果有:" + hits.getTotalHits() + "条");
        Iterator<SearchHit> iterator = hits.iterator();
        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next(); // 每个查询对象
            System.out.println(searchHit.getSourceAsString()); // 获取字符串格式打印
        }
        // 3 关闭连接
        client.close();
    }

这里需要说明,默认词条查询是将每个字作为索引进行查找,使用词(比如全文)进行查找是找不到的。单一使用有点鸡肋,需要借助分词器组合使用。


⑤ 模糊查询(fuzzy)

实例代码:

   @Test
    public void fuzzy() {
        // 1 模糊查询
        SearchResponse searchResponse = client.prepareSearch("my-blog").setTypes("article")
                .setQuery(QueryBuilders.fuzzyQuery("content", "大")).get();
        // 2 打印查询结果
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象
        System.out.println("查询结果有:" + hits.getTotalHits() + "条");
        Iterator<SearchHit> iterator = hits.iterator();
        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next(); // 每个查询对象
            System.out.println(searchHit.getSourceAsString()); // 获取字符串格式打印
        }
        // 3 关闭连接
        client.close();
    }

控制台打印:


【9】映射mappings

上面创建的索引默认映射信息http://192.168.18.128:9200/my-blog?pretty


添加mapping的索引必须存在且该索引不能存在mapping,否则添加不成功。

实例代码:

   @Test
    public void createMapping() throws Exception {
        //1.添加mapping的索引必须存在;2.该索引不能存在mapping,否则添加不成功
        CreateIndexResponse blog = client.admin().indices().prepareCreate("my-blog2").get();
        System.out.println(blog);
        // 2设置mapping
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("article")
                .startObject("properties")
                .startObject("id1")
                .field("type", "string")
                .field("store", "yes")
                .endObject()
                .startObject("title2")
                .field("type", "string")
                .field("store", "no")
                .endObject()
                .startObject("content")
                .field("type", "string")
                .field("store", "yes")
                .endObject()
                .endObject()
                .endObject()
                .endObject();
        // 3 添加mapping
        PutMappingRequest mapping = Requests.putMappingRequest("my-blog2").type("article").source(builder);
        client.admin().indices().putMapping(mapping).get();
        // 4 关闭资源
        client.close();
    }

浏览器查询确认http://192.168.18.128:9200/_cat/indices:

查询索引明细http://192.168.18.128:9200/my-blog2?pretty:


总结,用java原生操作es十分麻烦,建议使用SpringData Elasticsearch官网。

相关实践学习
使用阿里云Elasticsearch体验信息检索加速
通过创建登录阿里云Elasticsearch集群,使用DataWorks将MySQL数据同步至Elasticsearch,体验多条件检索效果,简单展示数据同步和信息检索加速的过程和操作。
ElasticSearch 入门精讲
ElasticSearch是一个开源的、基于Lucene的、分布式、高扩展、高实时的搜索与数据分析引擎。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr(也是基于Lucene)。 ElasticSearch的实现原理主要分为以下几个步骤: 用户将数据提交到Elastic Search 数据库中 通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据 当用户搜索数据时候,再根据权重将结果排名、打分 将返回结果呈现给用户 Elasticsearch可以用于搜索各种文档。它提供可扩展的搜索,具有接近实时的搜索,并支持多租户。
目录
相关文章
|
18天前
|
Java
java原生发送http请求
java原生发送http请求
|
1月前
|
存储 Java 数据处理
|
6天前
|
Java 关系型数据库 MySQL
Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
【4月更文挑战第12天】Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
33 3
|
3天前
|
数据采集 前端开发 测试技术
《手把手教你》系列技巧篇(三十一)-java+ selenium自动化测试- Actions的相关操作-番外篇(详解教程)
【4月更文挑战第23天】本文介绍了网页中的滑动验证码的实现原理和自动化测试方法。作者首先提到了网站的反爬虫机制,并表示在本地创建一个没有该机制的网页,然后使用谷歌浏览器进行验证。接着,文章详细讲解了如何使用WebElement的click()方法以及Action类提供的API来模拟鼠标的各种操作,如右击、双击、悬停和拖动。
6 2
|
4天前
|
Web App开发 数据采集 Java
《手把手教你》系列技巧篇(三十)-java+ selenium自动化测试- Actions的相关操作下篇(详解教程)
【4月更文挑战第22天】本文介绍了在测试过程中可能会用到的两个功能:Actions类中的拖拽操作和划取字段操作。拖拽操作包括基本讲解、项目实战、代码设计和参考代码,涉及到鼠标按住元素并将其拖动到另一个元素上或指定位置。划取字段操作则介绍了如何在一段文字中随机选取一部分,包括项目实战、代码设计和参考代码。此外,文章还提到了滑动验证的实现,并提供了相关的代码示例。
32 2
|
18天前
|
Java Maven 索引
java 链接Elasticsearch
java 链接Elasticsearch
|
1月前
|
Java
elasticsearch使用java程序添加删除修改
elasticsearch使用java程序添加删除修改
9 0
|
1月前
|
自然语言处理 Java
这是什么操作?java中的变量竟然可以先使用后声明?
这是什么操作?java中的变量竟然可以先使用后声明?
14 0
|
1月前
|
SQL Java
使用java中的String类操作复杂的字符串
使用java中的String类操作复杂的字符串
9 0
|
1月前
|
Java
java操作字符串
java操作字符串
9 1