人人都应该会的Elasticsearch API开发

一 概述

maven项目使用java api操作ES

Elasticsearc是基于lucene实现,隐藏复杂性,提供了简单易用的restful-api接口 java api接口(还有其他语言)

它是一个实时分布式搜索引擎.它用于全文搜素,结构化对比和分析.

我们还要知道它的基本术语:

  1. Index(索引-数据库)
    索引包含一堆有相似结构的文档数据,比如可以有一个客户索引,商品分类索引,订单索引,索引有一个名称。一个index包含很多document,一个index就代表了一类类似的或者相同的document。比如说建立一个product index,商品索引,里面可能就存放了所有的商品数据,所有的商品document。

  2. Type(类型-表)
    每个索引里都可以有一个或多个type,type是index中的一个逻辑数据分类,一个type下的document,都有相同的field,比如博客系统,有一个索引,可以定义用户数据type,博客数据type,评论数据type。
    商品index,里面存放了所有的商品数据,商品document
    但是商品分很多种类,每个种类的document的field可能不太一样,比如说电器商品,可能还包含一些诸如售后时间范围这样的特殊field;生鲜商品,还包含一些诸如生鲜保质期之类的特殊field

  3. Document(文档-行)
    文档是es中的最小数据单元,一个document可以是一条客户数据,一条商品分类数据,一条订单数据,通常用JSON数据结构表示,每个index下的type中,都可以去存储多个document。

  4. Field(字段-列)
    Field是Elasticsearch的最小单位。一个document里面有多个field,每个field就是一个数据字段。

二、环境

    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>5.2.2</version>
      </dependency>
      <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>5.2.2</version>
      </dependency>
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.9.0</version>
    </dependency>

三、基本操作

package cn.zhangyu.util;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ElasticSearchClient {
    public  PreBuiltTransportClient getClient() {
        Settings settings = Settings.builder().put("cluster.name","my-application").build();
        PreBuiltTransportClient client = new PreBuiltTransportClient(settings);
        try {
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.13.82.17"), 9300));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return client;
    }
}
import cn.zhangyu.util.ElasticSearchClient;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class ElasticSearchApp {
    ElasticSearchClient elasticSearchClient = new ElasticSearchClient();
    //创建索引
    @Test
    public void createIndex() {
        elasticSearchClient.getClient().admin().indices().prepareCreate("blog2").get();
        elasticSearchClient.getClient().close();
    }
    //删除索引
    public void delIndex(){
        elasticSearchClient.getClient().admin().indices().prepareDelete("blog2").get();
        elasticSearchClient.getClient().close();
    }
    //新建文档  源数据为json字符串
    @Test
    public void createDocumentByJson(){
        //1 准备文档数据
        String json = "{" + "\"id\":\"1\"," + "\"title\":\"基于Lucene的搜索服务器\","
                + "\"content\":\"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"" + "}";
        //2 创建文档
        IndexResponse response = elasticSearchClient.getClient().prepareIndex("blog", "article", "1")
                .setSource(json).execute().actionGet();
        //3 结果
        System.out.println("index:" + response.getIndex());
        System.out.println("type:" + response.getType());
        System.out.println("String:" + response.toString());
        //4 关闭连接
        elasticSearchClient.getClient().close();
    }
    //新建文档(源数据map方式添加json)
    @Test
    public void createDocumentByMap(){
        //1 准备数据源
        Map<String,Object>  json = new HashMap<>();
        json.put("id","2");
        json.put("title","基于Lucen的搜索服务器");
        json.put("content","它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");
        //2 创建文档
        IndexResponse response = elasticSearchClient.getClient().prepareIndex("blog", "article", "2")
                .setSource(json).execute().actionGet();
        //3 打印返回的结果
        System.out.println("index:" + response.getIndex());
        System.out.println("type:" + response.getType());
        System.out.println("id:" + response.getId());
        System.out.println("version:" + response.getVersion());
        System.out.println("result:" + response.getResult());
        //4 关闭连接
        elasticSearchClient.getClient().close();
    }
    //新建文档(源数据es构建器添加json)
    @Test
    public void createIndexByEs() throws IOException {
        XContentBuilder builder = XContentFactory.jsonBuilder().startObject()
                .field("id", "3")
                .field("title", "基于Lucene的搜索服务器")
                .field("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。")
                .endObject();
        IndexResponse indexResponse = elasticSearchClient.getClient().prepareIndex("blog", "article", "3")
                .setSource(builder).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 关闭连接
        elasticSearchClient.getClient().close();
    }
    //搜索数据(单索引)
    @Test
    public void getData(){
        //1 查询文档
        GetResponse response = elasticSearchClient.getClient()
                .prepareGet("blog","article","1")
                .get();
        //2 打印结果
        System.out.println(response.getSourceAsString());
        //3 关闭连接
        elasticSearchClient.getClient().close();
    }
    //搜索数据(多索引)
    @Test
    public void getMultiData(){
           //1 查询多个文档
        MultiGetResponse responses = elasticSearchClient.getClient().prepareMultiGet()
        //这里可以传递可变参数,即多个参数    (参考源码)
                .add("blog", "article", "1","2","3","4","5")
//                .add("blog", "article", "2")
//                .add("blog", "article", "3")
//                .add("blog", "article", "5")
                .get();
        //2 遍历结果 lambda表达式
        responses.forEach(itemResponses -> System.out.println(itemResponses.getResponse().getSourceAsString()));
        //3 关闭连接
        elasticSearchClient.getClient().close();
    }
    //更新文档数据
    @Test
    public void updateData() throws IOException, ExecutionException, InterruptedException {
        // 创建更新数据的请求对象
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index("blog");
        updateRequest.type("article");
        updateRequest.id("3");
        //会对没有的字段添加,已有的字段替换
        updateRequest.doc(XContentFactory.jsonBuilder().startObject()
                     .field("title", "基于Lucene的搜索服务器")
                     .field("content",
                                "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。大数据前景无限")
                     .field("createDate", "2017-8-22").endObject());
        //获取更新后的值
        UpdateResponse updateResponse = elasticSearchClient.getClient().update(updateRequest).get();
        //3 打印结果
        System.out.println("index:" + updateResponse.getIndex());
        System.out.println("type:" + updateResponse.getType());
        System.out.println("id:" + updateResponse.getId());
        System.out.println("version:" + updateResponse.getVersion());
        System.out.println("result:" + updateResponse.getResult());
        //4 关闭连接
        elasticSearchClient.getClient().close();
    }
    //更新文档数据(upsert)
    @Test
    public void upsertData() throws Exception{
        // 设置查询条件, 查找不到则添加
        IndexRequest indexRequest = new IndexRequest("blog", "article", "4");
        indexRequest.source(XContentFactory.jsonBuilder().startObject()
                .field("title", "搜索服务器")
                .field("content","它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。")
                .endObject());
        //设置更新,查找更新下面的设置
        UpdateRequest updateRequest = new UpdateRequest("blog", "article", "4");
        updateRequest.doc(XContentFactory.jsonBuilder().startObject()
                .field("user","张3").endObject()).upsert(indexRequest);
        elasticSearchClient.getClient().update(updateRequest).get();
        //4 关闭连接
        elasticSearchClient.getClient().close();
    }
    //删除文档数据
    @Test
    public void delData(){
        //1 删除文档
        DeleteResponse deleteResponse = elasticSearchClient.getClient().prepareDelete("blog", "article", "4").get();
        // 2 打印返回的结果
        System.out.println("index:" + deleteResponse.getIndex());
        System.out.println("type:" + deleteResponse.getType());
        System.out.println("id:" + deleteResponse.getId());
        System.out.println("version:" + deleteResponse.getVersion());
        System.out.println("found:" + deleteResponse.getResult());
    }
}
 //查询所有
    @Test
    public void matchAllQuery(){
        //1 执行查询
        SearchResponse searchResponse = elasticSearchClient.getClient().prepareSearch("blog").setTypes("article")
                .setQuery(QueryBuilders.matchAllQuery()).get();
        // 2 打印结果
        SearchHits hits = searchResponse.getHits();
        System.out.println("count :" + hits.getTotalHits() +" 条");
        hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
        // 3 关闭连接
        elasticSearchClient.getClient().close();
    }
    //对所有字段分词查询
    @Test
    public void queryStringQuery(){
        SearchResponse searchResponse = elasticSearchClient.getClient()
                .prepareSearch("blog").setTypes("article")
                .setQuery(QueryBuilders.queryStringQuery(" lucene")).get();
        // 2 打印结果
        SearchHits hits = searchResponse.getHits();
        System.out.println("count :" + hits.getTotalHits() +" 条");
        hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
        // 3 关闭连接
        elasticSearchClient.getClient().close();
    }
    /*通配符查询
      *:表示多个字符(任意的字符)
      ?:表示单个字符
     *
     */
    @Test
    public void wildcardQuery(){
        //通配符查询
        SearchResponse searchResponse = elasticSearchClient.getClient()
                .prepareSearch("blog").setTypes("article")
                .setQuery(QueryBuilders.wildcardQuery("content", "*全*")).get();
        //打印查询结果
        SearchHits hits = searchResponse.getHits();
        System.out.println("count :" + hits.getTotalHits() +" 条");
        hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
        //关闭连接
        elasticSearchClient.getClient().close();
    }
    //词条查询
    @Test
    public void termQuery(){
        SearchResponse searchResponse = elasticSearchClient.getClient()
                .prepareSearch("blog").setTypes("article")
                .setQuery(QueryBuilders.termQuery("content","它")).get();
        //打印查询结果
        SearchHits hits = searchResponse.getHits();
        System.out.println("count :" + hits.getTotalHits() +" 条");
        hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
        //关闭连接
        elasticSearchClient.getClient().close();
    }
    //模糊查询
    @Test
    public void fuzzyQuery(){
        SearchResponse searchResponse = elasticSearchClient.getClient()
                .prepareSearch("blog").setTypes("article")
                .setQuery(QueryBuilders.fuzzyQuery("title","lucene")).get();
        SearchHits hits = searchResponse.getHits();
        System.out.println("count :" + hits.getTotalHits() +" 条");
        hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
        elasticSearchClient.getClient().close();
    }

转载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值