Maven操作Elasticsearch创建index,Mapping,分页,高亮以及增删改查

本文主要讲述如何使用java-maven架构实现ElasticSearch增删改查,分页查询,高亮处理,以及创建Index,Mapping的方式

1. 导入pom.xml依赖

<dependencies>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.6.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-to-slf4j</artifactId>
            <version>2.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.24</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.1</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.1</version>
        </dependency>
    </dependencies>

2. 使用管理权限创建 Index和Mapping

Article实体类

package pojo;

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-07-31 11:06
 */
public class Article {
    private Long id;
    private String title;
    private String 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;
    }
}

创建Index和Mapping实现代码

package com.jwc.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import pojo.Article;

import java.net.InetAddress;

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-07-31 9:06
 */
public class ES2Test {
    private String host = "127.0.0.1";
    private int port = 9300;
    /*
    * 使用管理权限,单独创建索引
    * */
    @Test
    public void createIndex()throws Exception{
        // 创建客户端对象
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
        // 使用管理权限创建索引
        CreateIndexResponse response = transportClient.admin().indices().prepareCreate("blog2").get();
        System.out.println(response.isShardsAcked());
        System.out.println(response.isAcknowledged());
        // 关闭资源
        transportClient.close();
    }

    /*
     * 使用管理权限,删除索引
     * */
    @Test
    public void deleteIndex()throws Exception{
        // 创建客户端对象
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
        // 使用管理权限删除索引 使用字符串方式
        DeleteIndexResponse response = transportClient.admin().indices().prepareDelete("blog2").get();
        // 使用管理权限删除索引 使用对象方式
        DeleteIndexResponse blog2 = transportClient.admin().indices().delete(new DeleteIndexRequest("blog2")).get();
        // 返回执行结果
        System.out.println(response.isAcknowledged());
        // 关闭资源
        transportClient.close();
    }


    /*
     * 创建Mapping映射
     * */
    @Test
    public void createMapping()throws Exception{
        // 创建文档格式 mapping
        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("article")
                .startObject("properties")
                .startObject("id")
                .field("type", "long")
                .field("store", true)
                .endObject()
                .startObject("title")
                .field("type", "text")
                .field("analyzer", "ik_max_word")
                .field("store", true)
                .endObject()
                .startObject("content")
                .field("type", "text")
                .field("analyzer", "ik_max_word")
                .field("store", true)
                .endObject()
                .endObject()
                .endObject()
                .endObject();

        // 封装Mapping请求
        PutMappingRequest putMappingRequest = Requests.putMappingRequest("blog2").type("article").source(xContentBuilder);

        // 创建客户端对象
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
        // 判断要添加Mapping映射的索引是否存在
        IndicesExistsResponse indicesResponse = transportClient.admin().indices().exists(new IndicesExistsRequest("blog2")).get();
        // 如果不存在 那么创建索引
        if (!indicesResponse.isExists()){
            CreateIndexResponse blog2 = transportClient.admin().indices().prepareCreate("blog2").get();
            // 输出索引是否执行成功返回值
            System.out.println(blog2.isAcknowledged());
        }
        // 创建Mapping 映射
        PutMappingResponse putMappingResponse = transportClient.admin().indices().putMapping(putMappingRequest).get();
        // 关闭资源
        transportClient.close();
    }
}

3. 增删改查文档

3.1 添加文档

  private String host = "127.0.0.1";
  private int port = 9300;

	 /*
    * 使用实体类生成DOC文档
    * */
    @Test
    public void creatDocByBean()throws Exception{
        // 创建客户端对象
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
        // 创建实体类 Article
        Article article = new Article();
        article.setId(2L);
        article.setTitle("ElasticSearch是一个基于Lucene的搜索服务器");
        article.setContent("提供了一个分布式多用户能力的全文搜索引擎");
        // 把对象转换为Json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(article);
        // 使用客户端执行命令
        IndexResponse indexResponse = transportClient.prepareIndex("blog", "article", String.valueOf(article.getId())).setSource(jsonStr).get();
        // 关闭资源
        transportClient.close();
    }

3.2 删除文档

 	private String host = "127.0.0.1";
    private int port = 9300;

    /*
     * 使用实体类删除DOC文档
     * */
    @Test
    public void deleteDoc() throws Exception {
        // 创建客户端对象
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
        // 创建实体类 Article
        Article article = new Article();
        article.setId(1L);
        // 使用Object方式修改DOC 这里的Request对象最后一位参数是指 文档的唯一标识
        transportClient.prepareDelete("blog", "article", String.valueOf(article.getId())).get();
        // 关闭资源
        transportClient.close();
    }

3.3 修改文档

 	private String host = "127.0.0.1";
    private int port = 9300;
    /*
     * 使用实体类修改DOC文档
     * */
    @Test
    public void updateDocByBean()throws Exception{
        // 创建客户端对象
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
        // 创建实体类 Article
        Article article = new Article();
        article.setId(2L);
        article.setTitle("一个基于Lucene的搜索服务器");
        article.setContent("一个分布式多用户能力的全文搜索引擎");
        // 把对象转换为Json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(article);
        // 使用客户端执行修改命令
//        UpdateResponse updateResponse = transportClient.prepareUpdate("blog", "article", String.valueOf(article.getId())).setDoc(jsonStr).get();
        // 使用Object方式修改DOC 这里的Request对象最后一位参数是指 文档的唯一标识
         UpdateResponse objectResponse = transportClient.update(new UpdateRequest("blog","article",String.valueOf(article.getId())).doc(jsonStr)).get();
        // 关闭资源
        transportClient.close();
    }

3.4 分页查询文档数据

package com.jwc.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import pojo.Article;

import java.net.InetAddress;

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-07-31 9:06
 */
public class ES2Page {
    private String host = "127.0.0.1";
    private int port = 9300;
    /*
     * 批量添加数据
     * */
    @Test
    public void addBatch()throws Exception{
        // 创建客户端对象
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
        for (int i = 1 ; i<101 ;i++){
            // 创建实体类 Article
            Article article = new Article();
            article.setId(Long.parseLong(String.valueOf(i)));
            article.setTitle("一个基于Lucene的搜索服务器"+i);
            article.setContent("一个分布式多用户能力的全文搜索引擎"+i);
            // 把对象转换为Json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(article);
            // 添加数据
           transportClient.prepareIndex("blog2","article",String.valueOf(article.getId())).setSource(jsonStr).get();
            // 关闭资源
        }
        transportClient.close();
    }

    /*
     * 分页查询
     * */
    @Test
    public void testPage()throws Exception{
        // 创建客户端对象
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
        // 查询
        SearchRequestBuilder searchRequestBuilder = transportClient
                .prepareSearch("blog2")
                .setTypes("article")
                .setQuery(QueryBuilders.matchAllQuery());
        // 处理分页
        searchRequestBuilder.setFrom(0); // 设置从那一条开始
        searchRequestBuilder.setSize(5); // 设置每页显示条数
        searchRequestBuilder.addSort("id", SortOrder.ASC); // 设置排序规则
        // 执行查询命令
        SearchResponse searchResponse = searchRequestBuilder.get();
        // 获取命中的条数
        SearchHits hits = searchResponse.getHits();
        // 输出总记录数
        System.out.println(hits.getTotalHits());
        // 循环展示
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        // 关闭资源
        transportClient.close();
    }
}

4. 高亮显示

package com.jwc.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.search.SearchRequestBuilder;
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.InetSocketTransportAddress;
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.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import pojo.Article;

import javax.sound.midi.Soundbank;
import java.net.InetAddress;

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-07-31 9:06
 */
public class ES2HightLight {
    private String host = "127.0.0.1";
    private int port = 9300;

    /*
     * 处理高亮
     * */
    @Test
    public void testHighLight() throws Exception {
        // 创建客户端对象
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
        SearchRequestBuilder searchRequestBuilder = transportClient
                .prepareSearch("blog2")
                .setTypes("article")
                // 词条查询符合高亮查询基本要求
                .setQuery(QueryBuilders.termQuery("title","基于"));
        // 处理高亮字段
        HighlightBuilder highLight = new HighlightBuilder();
        // 添加前缀
        highLight.preTags("<font color = 'red'>");
        // 添加字段
        highLight.field("title");
        // 添加后缀
        highLight.postTags("</font>");
        // 设置高亮
        searchRequestBuilder.highlighter(highLight);
        // 执行命令
        SearchResponse searchResponse = searchRequestBuilder.get();
        // 获取高亮查询结果
        SearchHits hits = searchResponse.getHits();
        for (SearchHit hit : hits) {
            // 获取高亮字段
            Text[] titles = hit.getHighlightFields().get("title").fragments();
            for (Text title : titles) {
                System.out.println(title.toString());
            }
        }
        // 关闭资源
        transportClient.close();
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叫我三胖哥哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值