ElasticSearch入门案例

1. 导入maven依赖

<!--导入elasticsearch坐标-->

    <dependencies>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.6.8</version>
        </dependency>
        <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>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>

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

    </dependencies>

2. JavaAPI操作ElasticSearch

  2.1 创建索引库

  

package com.pomelo.index;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.Article;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuilder;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequestBuilder;
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.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

import java.net.InetAddress;

public class IndexManager {

    //创建连接对象
    public TransportClient getClient() throws Exception {
        /**
         * 1:配置es信息
         * 等价与:Settings settings1 = Settings.builder().put("cluster.name","elasticsearch").build();
         * 如果做集群,那么就必须使用这么上面这种定义,并且把集群名更改成自己自己设置的集群名。
         */
        Settings settings = Settings.EMPTY;

        //2: 创建客户端对象
        TransportClient transportClient = new PreBuiltTransportClient(settings);
        //3: 指定服务器的地址和ip
        transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9300));

        //返回
        return transportClient;
    }

    @Test  //创建索引库
    public void createIndex() throws Exception {
        //1. 获取连接
        TransportClient transportClient = this.getClient();
        //2. 创建索引库 http://localhost:9200/blog---put请求
        CreateIndexResponse indexResponse = transportClient.admin().indices().prepareCreate("blog").get();
        System.out.println(indexResponse.isShardsAcked());
        //3. 释放资源
        transportClient.close();
    }

    @Test //创建文档
    public void createIndexDocument() throws Exception {
        //1. 获取连接
        TransportClient transportClient = this.getClient();
        //2. 保存数据
        XContentBuilder contentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .field("id",1)
                .field("title","elasticsearch是一个基于lucene的搜索服务")
                .field("content","ElasticSearch是一个基于Lucene的搜索服务器。" +
                        "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。" +
                        "Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布," +
                        "是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定," +
                        "可靠,快速,安装使用方便。")
                .endObject();
        /**
         * 把json数据储存到es索引库中
         * 参数1:索引库
         * 参数2:类型/分类
         * 参数3:id
         * 如果没有指定id,就会用uuid生成的主键id
         */
        IndexRequestBuilder requestBuilder = transportClient.prepareIndex("blog", "content");
        IndexResponse indexResponse = requestBuilder.setSource(contentBuilder).get();
        System.out.println(indexResponse.status());
        //3. 释放资源
        transportClient.close();
    }

    @Test //基于实体类的方式创建文档数据
    public void createIndexDocumentByDomain() throws Exception {
        //1. 获取连接
        TransportClient client = this.getClient();
        //2. 保存数据
        Article article = new Article();
        article.setId(2);
        article.setTitle("solr是一个基于lucene的搜索服务");
        article.setContent("solr是一个基于Lucene的搜索服务器" +
                " 它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。" +
                " solr是用Java开发的,并作为Apache许可条款下的开放源码发布," +
                " 是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定," +
                " 可靠,快速,安装使用方便。");

        //转成json
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(article);

        IndexRequestBuilder requestBuilder = client.prepareIndex("blog", "content","1");
        IndexResponse indexResponse = requestBuilder.setSource(json, XContentType.JSON).get();
        System.out.println(indexResponse.status());

        //3. 释放资源
        client.close();
    }

    @Test //修改文档
    public void updateIndexDocument() throws Exception {
        //1. 获取连接
        TransportClient client = this.getClient();
        //2. 修改文档
        Article article = new Article();
        article.setId(3);
        article.setTitle("elasticsearch是一个基于lucene的搜索服务");
        article.setContent("elasticsearch是一个基于Lucene的搜索服务器" +
                " 它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。" +
                " elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布," +
                " 是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定," +
                " 可靠,快速,安装使用方便。");

        //转成json
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(article);

        UpdateRequestBuilder prepareUpdate = client.prepareUpdate("blog", "content", "1");
        UpdateResponse updateResponse = prepareUpdate.setDoc(json, XContentType.JSON).get();
        System.out.println(updateResponse.status());

        //3. 释放资源
        client.close();
    }

    @Test //删除文档
    public void deleteIndexDocument() throws Exception {
        //1. 获取连接
        TransportClient client = this.getClient();
        //2. 删除
        DeleteRequestBuilder deleteRequestBuilder = client.prepareDelete("blog", "content", "1");
        DeleteResponse deleteResponse = deleteRequestBuilder.get();
        System.out.println(deleteResponse.status());
        //3. 释放资源
        client.close();
    }

    /*
    //创建mapping规则
    "mappings": {
        "content": {
            "properties": {
                "id": {
                    "store": true,
                    "type": "long"
                },
                "title": {
                    "analyzer": "ik_smart",
                    "store": true,
                    "type": "text"
                },
                "content": {
                    "analyzer": "ik_smart",
                    "store": true,
                    "type": "text"
                }
            }
        }
    },
     */
    @Test
    public void createMapping() throws Exception {
        //1. 获取连接
        TransportClient client = this.getClient();
        //2. 创建索引库
        CreateIndexResponse indexResponse = client.admin().indices().prepareCreate("blog2").get();
        //3. 如果索引库存在,就创建mapping规则
        if(indexResponse.isAcknowledged()){
            XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject()
                    .startObject("content")
                    .startObject("properties")
                    .startObject("id").field("type","long").field("store",true).endObject()
                    //ik_max_word 最细切法(如果还能切继续切,切到没有为止) 和 ik_smart 最小切法
                    .startObject("title").field("type", "text").field("store", true).field("analyzer", "ik_smart").endObject()
                    .startObject("content").field("type", "text").field("store", true).field("analyzer", "ik_smart").endObject()
                    .endObject()
                    .endObject()
                    .endObject();
            PutMappingRequestBuilder mappingRequestBuilder = client.admin().indices().preparePutMapping("blog2").setType("content");
            PutMappingResponse mappingResponse = mappingRequestBuilder.setSource(xContentBuilder).get();
            System.out.println(mappingResponse.isAcknowledged());
        }
        //4. 关闭资源
        client.close();
    }

}

 

  2.2 全文检索

  

package com.pomelo.search;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
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.QueryBuilder;
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 java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

public class SearchManager {

    //创建连接
    public TransportClient getClient() throws Exception {
        Settings settings = Settings.EMPTY;
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        return client;
    }

    @Test //创建索引库
    public void createIndexDocument() throws Exception {
        //1. 获取连接
        TransportClient client = this.getClient();

        //2. 创建文档
        Map<String, Object> map = new HashMap<>();
        for (int i = 1; i <= 30; i++) {
            map.put("id", i);
            map.put("title", i + " ,elasticsearch和solr都还行");
            map.put("content", i + " ,学习elasticsearch很快乐好难记");
            map.put("price", i + 100);

            IndexRequestBuilder requestBuilder = client.prepareIndex("blog3", "article", i + "");
            IndexResponse indexResponse = requestBuilder.setSource(map).get();
            System.out.println(indexResponse.status());
        }
        //3. 关闭资源
        client.close();
    }

    @Test //查询
    public void searchMain() throws Exception {
        //1. 获取连接对象
        TransportClient client = this.getClient();

        /**
         * 2. 查询条件:
         1:查询全部  QueryBuilders.matchAllQuery()
         2、字符串搜索 QueryBuilders.queryStringQuery(“elasticsearch”)
         3、词条搜索  QueryBuilders.termQuery(“content”,“elasticsearch”)
         4、根据ID搜索 QueryBuilders.idsQuery().addIds("1","2");
         *
         */
        //QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
         //QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("elasticsearch好多API,字符串搜索会分词");
        //QueryBuilder queryBuilder = QueryBuilders.termQuery("content", "elasticsearch词条搜索不会分词");
        //QueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds("1", "2", "3");
        QueryBuilder queryBuilder = QueryBuilders.termQuery("title", "solr");


        int pageNum = 1;  //当前页
        int pageSize = 10; //每页大小

        //高亮对象
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<span style='color:red'>");  //开始标签
        highlightBuilder.field("title");  //高亮字段
        highlightBuilder.postTags("</span>");  //结束标签

        //3. 执行查询
        SearchResponse searchResponse = client.prepareSearch("blog3")  //指定搜索库 多个用逗号分开
                //  指定搜索的类型,多个用逗号分开
                .setTypes("article")
                // 排序
                .addSort("price", SortOrder.ASC)
                //  分页
                .setFrom((pageNum - 1) * pageSize)
                .setSize(pageSize)
                //设置高亮
                .highlighter(highlightBuilder)
                //设置搜索条件
                .setQuery(queryBuilder)
                //  返回
                .get();

        //4. 获取搜索结果
        SearchHits hits = searchResponse.getHits();
        System.out.println("搜索结果有:" + hits.getTotalHits() + "条数据");
        for (SearchHit hit : hits) {

            //索引库中的文档数据
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            System.out.println("id: " + sourceAsMap.get("id"));
            System.out.println("content: " + sourceAsMap.get("content"));
            System.out.println("price: " + sourceAsMap.get("price"));

            //获取高亮内容
            if(hit.getHighlightFields() != null && hit.getHighlightFields().get("title") != null){
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                if(titles != null && titles.length > 0){
                    System.out.println("高亮内容是:" + titles[0].string());
                }else {
                    System.out.println("title: " + sourceAsMap.get("title"));
                }
            }else {
                System.out.println("title: " + sourceAsMap.get("title"));
            }
            System.out.println("=========================================================");
        }

        //5. 释放连接
        client.close();
    }


}

 

posted @ 2019-08-29 19:54  闲云陌路  阅读(512)  评论(0编辑  收藏  举报