zoukankan      html  css  js  c++  java
  • elasticsearch的java api

    一、pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.example</groupId>
        <artifactId>A02elasticsearch</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <dependencies>
            <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
            <dependency>
                <groupId>org.elasticsearch</groupId>
                <artifactId>elasticsearch</artifactId>
                <version>7.4.0</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>transport</artifactId>
                <version>7.4.0</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-to-slf4j -->
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-to-slf4j</artifactId>
                <version>2.13.3</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>1.7.30</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-simple</artifactId>
                <version>1.7.30</version>
                <scope>test</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/log4j/log4j -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/junit/junit -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13</version>
                <scope>test</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.12</version>
                <scope>provided</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.11.2</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>2.11.2</version>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.9</source>
                        <target>1.9</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    </project>

    二、bean

    package com.wuxi.bean;
    
    import lombok.Data;
    
    @Data
    public class Article {
        private Long id;
        private String title;
        private String content;
    }

    三、测试

    package com.wuxi.test;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.wuxi.bean.Article;
    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.common.xcontent.XContentBuilder;
    import org.elasticsearch.common.xcontent.XContentFactory;
    import org.elasticsearch.common.xcontent.XContentType;
    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.fetch.subphase.highlight.HighlightField;
    import org.elasticsearch.transport.client.PreBuiltTransportClient;
    import org.junit.Test;
    
    import java.net.InetAddress;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    
    public class MyElasticSearchTest {
        /**
         * 创建索引库
         *
         * @throws Exception
         */
        @Test
        public void createIndex() throws Exception {
            //1、创建一个Settings对象,相当于是一个配置信息。主要配置集群名称。
            Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
            //2、创建一个客户端client对象
            TransportClient client = new PreBuiltTransportClient(settings);
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
            //3、使用client对象创建一个索引库
            Map<String, Object> settingsMap = new HashMap<>();
            Map<String, Object> indexMap = new HashMap<>();
            indexMap.put("number_of_shards", "5");
            indexMap.put("number_of_replicas", "1");
            settingsMap.put("index", indexMap);
            client.admin().indices().prepareCreate("index_hello").setSettings(settingsMap)
                    //执行操作
                    .get();
            //4、关闭client对象
            client.close();
        }
    
        /**
         * 添加mapping映射
         *
         * @throws Exception
         */
        @Test
        public void setMappings() throws Exception {
            //创建一个Settings对象
            Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
            //创建一个TransportClient对象
            TransportClient client = new PreBuiltTransportClient(settings);
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
            //创建一个Mappings信息
            XContentBuilder builder = XContentFactory.jsonBuilder()
                    .startObject()
                    .startObject("properties")
                    .startObject("id")
                    .field("type", "long")
                    .field("store", true)
                    .endObject()
                    .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();
            //使用client把mapping信息设置到索引库中
            client.admin().indices()
                    .preparePutMapping("index_hello")
                    .setType("_doc")
                    .setSource(builder)
                    .get();
            //关闭client对象
            client.close();
        }
    
        /**
         * 添加文档
         *
         * @throws Exception
         */
        @Test
        public void testAddDocument() throws Exception {
            //创建一个Settings对象
            Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
            //创建一个TransportClient对象
            TransportClient client = new PreBuiltTransportClient(settings);
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
            //创建一个文档对象
            XContentBuilder builder = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("id", 1l)
                    .field("title", "这是文档的标题")
                    .field("content", "这是文档的内容,是一段中文")
                    .endObject();
            //把文档对象添加到索引库
            client.prepareIndex()
                    .setIndex("index_hello")
                    .setType("_doc")
                    .setId("1")
                    .setSource(builder)
                    .get();
            //关闭
            client.close();
        }
    
        /**
         * json方式添加文档
         *
         * @throws Exception
         */
        @Test
        public void testAddDocument2() throws Exception {
            //创建一个Settings对象
            Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
            //创建一个TransportClient对象
            TransportClient client = new PreBuiltTransportClient(settings);
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
            //创建生成json字符串
            Article article = new Article();
            article.setId(2l);
            article.setTitle("使用json方式添加文档");
            article.setContent("就统筹推进常态化疫情防控和经济社会发展工作、谋划“十四五”时期经济社会发展进行调研。");
            String jsonDocument = new ObjectMapper().writeValueAsString(article);
            //使用client对象把文档写入索引库
            client.prepareIndex("index_hello", "_doc", "2")
                    .setSource(jsonDocument, XContentType.JSON)
                    .get();
            //关闭
            client.close();
        }
    
        /**
         * 根据id查询文档
         *
         * @throws Exception
         */
        @Test
        public void testSearchById() throws Exception {
            //创建一个Settings对象
            Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
            //创建一个TransportClient对象
            TransportClient client = new PreBuiltTransportClient(settings);
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
            //创建一个查询对象
            QueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds("1", "2");
            //执行查询
            SearchResponse searchResponse = client.prepareSearch("index_hello")
                    .setTypes("_doc")
                    .setQuery(queryBuilder)
                    .get();
            //取查询结果
            SearchHits searchHits = searchResponse.getHits();
            //取查询结果的总记录数
            System.out.println("查询结果总记录数:" + searchHits.getTotalHits());
            //查询结果列表
            Iterator<SearchHit> iterator = searchHits.iterator();
            while (iterator.hasNext()) {
                SearchHit searchHit = iterator.next();
                //打印文档对象,以json格式输出
                System.out.println(searchHit.getSourceAsString());
                //取文档的属性
                System.out.println("--------文档的属性");
                Map<String, Object> document = searchHit.getSourceAsMap();
                System.out.println(document.get("id"));
                System.out.println(document.get("title"));
                System.out.println(document.get("content"));
            }
            //关闭
            client.close();
        }
    
        /**
         * 根据关键词查询文档
         *
         * @throws Exception
         */
        @Test
        public void testSearchByTerm() throws Exception {
            //创建一个Settings对象
            Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
            //创建一个TransportClient对象
            TransportClient client = new PreBuiltTransportClient(settings);
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
            //创建一个查询对象
            QueryBuilder queryBuilder = QueryBuilders.termQuery("title", "文档");
            //执行查询
            SearchResponse searchResponse = client.prepareSearch("index_hello")
                    .setTypes("_doc")
                    .setQuery(queryBuilder)
                    .get();
            //取查询结果
            SearchHits searchHits = searchResponse.getHits();
            //取查询结果的总记录数
            System.out.println("查询结果总记录数:" + searchHits.getTotalHits());
            //查询结果列表
            Iterator<SearchHit> iterator = searchHits.iterator();
            while (iterator.hasNext()) {
                SearchHit searchHit = iterator.next();
                //打印文档对象,以json格式输出
                System.out.println(searchHit.getSourceAsString());
                //取文档的属性
                System.out.println("--------文档的属性");
                Map<String, Object> document = searchHit.getSourceAsMap();
                System.out.println(document.get("id"));
                System.out.println(document.get("title"));
                System.out.println(document.get("content"));
            }
            //关闭
            client.close();
        }
    
        /**
         * 根据分词查询,分页查询,高亮显示
         *
         * @throws Exception
         */
        @Test
        public void testQueryStringQuery() throws Exception {
            //创建一个Settings对象
            Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
            //创建一个TransportClient对象
            TransportClient client = new PreBuiltTransportClient(settings);
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
            //创建一个查询对象
            QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("这是一个文档")
                    .defaultField("title");
            //高亮显示
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("title");
            highlightBuilder.preTags("<em>");
            highlightBuilder.postTags("</em>");
            //执行分页查询
            SearchResponse searchResponse = client.prepareSearch("index_hello")
                    .setTypes("_doc")
                    .setQuery(queryBuilder)
                    //页数
                    .setFrom(0)
                    //每页条数
                    .setSize(5)
                    //设置高亮
                    .highlighter(highlightBuilder)
                    .get();
            //取查询结果
            SearchHits searchHits = searchResponse.getHits();
            //取查询结果的总记录数
            System.out.println("查询结果总记录数:" + searchHits.getTotalHits());
            //查询结果列表
            Iterator<SearchHit> iterator = searchHits.iterator();
            while (iterator.hasNext()) {
                SearchHit searchHit = iterator.next();
                //打印文档对象,以json格式输出
                System.out.println(searchHit.getSourceAsString());
                //取文档的属性
                System.out.println("--------文档的属性");
                Map<String, Object> document = searchHit.getSourceAsMap();
                System.out.println(document.get("id"));
                System.out.println(document.get("title"));
                System.out.println(document.get("content"));
                System.out.println("********高亮显示");
                Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
                System.out.println(highlightFields);
                //取title高亮显示的结果
                HighlightField field = highlightFields.get("title");
                Text[] fragments = field.getFragments();
                if (fragments != null) {
                    String title = fragments[0].toString();
                    System.out.println(title);
                }
            }
            //关闭
            client.close();
        }
    }
  • 相关阅读:
    APP上线碰到的问题:Non-public API usage
    点语法
    strlen、strcpy、strcat的实现
    2. I/O模型基本说明
    1. 同步、异步、阻塞、非阻塞
    8. 负载均衡请求转发实现
    7.负载均衡算法
    6. Nginx配置示例-高可用集群
    5. Nginx配置示例-动静分离
    4. Nginx配置示例-负载均衡
  • 原文地址:https://www.cnblogs.com/linding/p/13693992.html
Copyright © 2011-2022 走看看