ElasticSearch笔记(二)

ElasticSearch笔记(二)

1. 用Java操作ElasticSearch

1. 导入maven坐标

 <dependencies>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.6.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>7.6.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.6.1</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.12</version>
        </dependency>
    </dependencies>

2. 建立连接,创建client对象

 private  TransportClient client;
    @Before
    public void init() throws Exception{
        //创建一个Setting对象,相当于配置信息
        Settings settings = Settings.builder()
                .put("cluster.name","my-elasticsearch")
                .build();
        //创建Client对象
        client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9301))
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9302))
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9303));
    }

3. 创建索引

   @Test
    public void createIdnex() throws  Exception {
        //创建一个索引库
        client.admin().indices().prepareCreate("hello_index").get();
        //关闭client
        client.close();
    }

4. 创建映射mapping

 @Test
    public void setMappings() throws Exception {
        //创建一个Mappings信息,必须使用json格式
        XContentBuilder xContentBuilder = 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把索引信息设置到索引库
        client.admin().indices()
                .preparePutMapping("hello_index")
                .setType("_doc")
                .setSource(xContentBuilder)
                .get();
        client.close();
    }

5. 添加文档

@Test
    public void AddDocument() throws Exception{
        //创建一个文档对象
        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                    .field("id",1L)
                    .field("title","多表查询")
                    .field("content","当我们使用两张或者两张以上的表联合查询时,就会产生四种关系")
                .endObject();
        //把文档对象添加到索引库
        client.prepareIndex()
                .setIndex("hello_index")
                .setType("_doc")
                .setId("2")
                .setSource(xContentBuilder)
                .get();
        client.close();
    }

6. 查询文档

查询文档的方式有,id,term,QueryString.
1.根据ID

 @Test
    public void SearchById() throws Exception {
        //创建一个查询对象
        QueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds("1");
        Search(queryBuilder,"id");
    }

Search方法用来显示查询结果

public void Search(QueryBuilder queryBuilder, String highlightField) throws Exception{
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //高亮显示的字段
        highlightBuilder.field(highlightField);
        highlightBuilder.preTags("<em>");
        highlightBuilder.postTags("</em>");
        SearchResponse searchResponse = client.prepareSearch("hello_index")
                .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();
            System.out.println(searchHit.getSourceAsString());
            Map<String,Object> document = searchHit.getSourceAsMap();
            System.out.println(document.get("id"));
            System.out.println(document.get("title"));
            System.out.println(document.get("content"));
            Map<String,HighlightField> highlightFieldMap =searchHit.getHighlightFields();
            System.out.println(highlightFieldMap);
            //取title高亮显示的结果
            HighlightField field = highlightFieldMap.get(highlightField);
            Text[] fragment = field.getFragments();
            if (fragment != null) {
                String title = fragment[0].toString();
                System.out.println(title);
            }
        }
        client.close();
    }

2.根据Term

  @Test
    public void SearchByTrem() throws Exception {
        //参数一字段,参数二关键词
        QueryBuilder queryBuilder = QueryBuilders.termQuery("title","一个人");
        Search(queryBuilder,"title");
    }

3.根据QueryString

 @Test
    public void SearchByQueryString() throws Exception {
        QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("我们的爱")
                                        .defaultField("content");
        Search(queryBuilder,"content");
    }