Elasticsearch-javaAPI

1.创建maven项目

编辑器:IDEA
创建项目完成后,将maven配置到自己安装的位置,并将setting文件和repository配置好。

2.pom文件依赖

<dependencies>
  <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <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>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

3.javaAPI操作

在这里插入图片描述

package com.dengdan.es;

import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Requests;
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.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class ESTest {
    /**
     * 客户端
     */
    private PreBuiltTransportClient client = null;

    /**
     * 获取客户端
     *
     * @return
     * @throws UnknownHostException
     */
    @Before
    public void getClient() throws UnknownHostException {
        //获取集群信息
        Settings settings = Settings.builder().put("cluster.name", "my-application").build();
        //获取客户端
        client = new PreBuiltTransportClient(settings);
        //连接到具体的主机
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("master"), 9300));
        System.out.println(client.toString());
    }

    /**
     * 创建索引
     */
    @Test
    public void createIndex() {
        //执行创建索引操作
        client.admin().indices().prepareCreate("blog4").get();

        client.close();
    }

    /**
     * 删除索引
     */
    @Test
    public void delIndex() {
        //执行删除索引的操作
        client.admin().indices().prepareDelete("blog").get();
        //关闭客户端
        client.close();
    }

    /**
     * 插入数据 以json格式
     */
    @Test
    public void createDocumentByJson() {
        // 1 文档数据准备
        String json = "{" + "\"id\":\"1\"," + "\"title\":\"基于Lucene的搜索服务器\","
                + "\"content\":\"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"" + "}";

        // 2 创建文档
        IndexResponse response = client.prepareIndex("blog", "article", "1").setSource(json).execute().actionGet();

        //3.打印返回信息
        System.out.println(response.getIndex());
        System.out.println(response.getType());
        System.out.println(response.getResult());
        System.out.println(response.getId());

        //4.关闭客户端
        client.close();
    }

    /**
     * 插入数据 以map格式
     */
    @Test
    public void createDocumentByMap() {
        // 1 文档数据准备
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", "2");
        map.put("title", "基于Lucene的搜索服务器");
        map.put("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");


        // 2 创建文档
        IndexResponse response = client.prepareIndex("blog", "article", "2").setSource(map).execute().actionGet();

        //3.打印返回信息
        System.out.println(response.getIndex());
        System.out.println(response.getType());
        System.out.println(response.getResult());
        System.out.println(response.getId());

        //4.关闭客户端
        client.close();
    }

    /**
     * 插入文档 以ES 构建器
     */
    @Test
    public void createDocumentByES() throws IOException {
        //1.通过es自带的帮助类,构建json数据
        XContentBuilder data = XContentFactory.jsonBuilder().startObject()
                .field("id", 4)
                .field("title", "虎哥")
                .field("content", "吃饭睡觉打豆豆")
                .endObject();

        // 2 创建文档
        IndexResponse response = client.prepareIndex("blog", "article", "3").setSource(data).execute().actionGet();

        //3.打印返回信息
        System.out.println(response.getIndex());
        System.out.println(response.getType());
        System.out.println(response.getResult());
        System.out.println(response.getId());

        //4.关闭客户端
        client.close();
    }

    /**
     * 搜索文档数据
     */
    @Test
    public void getData() {
        //1.获取数据
        GetResponse response = client.prepareGet("blog", "article", "1").get();
        //2.打印数据
        System.out.println(response.getSourceAsString());
        //3.关闭连接
        client.close();
    }

    /**
     * 搜索多条文档数据
     */
    @Test
    public void getMultiData() {
        //1.获取多条文档数据
        MultiGetResponse itemResponses = client.prepareMultiGet().add("blog", "article", "1")
                .add("blog", "article", "1", "2", "3")
                .add("blog", "article", "2")
                .get();
        //2.打印数据
        for (MultiGetItemResponse response : itemResponses) {
            GetResponse response1 = response.getResponse();
            if (response1.isExists()) {
                //打印每一条数据
                System.out.println(response1.getSourceAsString());
            }
        }
        //3.关闭客户端
        client.close();
    }

    /**
     * 更新文档数据
     */
    @Test
    public void update() throws IOException, ExecutionException, InterruptedException {
        //1.获取更新请求
        UpdateRequest request = new UpdateRequest("blog", "article", "3")
                .doc(XContentFactory.jsonBuilder().startObject()
                        .field("id", "3")
                        .field("title", "班长")
                        .field("content", "班长吃饭睡觉打豆豆")
                        .endObject());

        //2.执行更新操作
        client.update(request).get();

        //3.关闭客户端
        client.close();
    }

    /**
     * 更新数据,找不到就插入数据
     */
    @Test
    public void upsert() throws IOException, ExecutionException, InterruptedException {

        //1.获取插入请求
        IndexRequest indexRequest = new IndexRequest("blog", "article", "5")
                .source(XContentFactory.jsonBuilder().startObject()
                        .field("id", "3")
                        .field("title", "舒总")
                        .field("content", "班长吃饭睡觉打豆豆")
                        .endObject());

        //2.获取更新请求
        UpdateRequest request = new UpdateRequest("blog", "article", "5")
                .doc(XContentFactory.jsonBuilder().startObject()
                        .field("id", "3")
                        .field("title", "班长")
                        .field("content", "班长吃饭睡觉打豆豆,撩妹")
                        .endObject()).upsert(indexRequest);

        //3.执行更新操作
        client.update(request).get();

        //4.关闭客户端
        client.close();
    }

    /**
     * 删除文档数据
     */
    @Test
    public void delete() {
        //执行删除操作
        DeleteResponse deleteResponse = client.prepareDelete("blog", "article", "5").get();
        //关闭客户端
        client.close();
    }

    /**
     * 查询所有数据
     */
    @Test
    public void matchAll() {

        //1.执行相关查询
        SearchResponse response = client.prepareSearch("blog").setTypes("article").setQuery(
                QueryBuilders.matchAllQuery()).get();

        SearchHits hits = response.getHits();
        //2.打印出命中多少文档数据
        System.out.println(hits.getTotalHits());

        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //3.打印出实际数据
            System.out.println(sourceAsString);
        }
        //4.关闭客户端
        client.close();
    }

    /**
     * 分词查询
     */
    @Test
    public void query() {
        //1.执行相关查询
        SearchResponse response = client.prepareSearch("blog").setTypes("article").setQuery(
                QueryBuilders.queryStringQuery("分布式")).get();

        SearchHits hits = response.getHits();
        //2.打印出命中多少文档数据
        System.out.println(hits.getTotalHits());

        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //3.打印出实际数据
            System.out.println(sourceAsString);
        }
        //4.关闭客户端
        client.close();
    }

    /**
     * 通配符查询
     */
    @Test
    public void wildCard() {
        //1.执行相关查询
        SearchResponse response = client.prepareSearch("blog").setTypes("article").setQuery(
                QueryBuilders.wildcardQuery("content", "*分")).get();

        SearchHits hits = response.getHits();
        //2.打印出命中多少文档数据
        System.out.println(hits.getTotalHits());

        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //3.打印出实际数据
            System.out.println(sourceAsString);
        }
        //4.关闭客户端
        client.close();
    }

    /**
     * 词条查询
     */
    @Test
    public void termQuery() {
        //1.执行相关查询
        SearchResponse response = client.prepareSearch("blog").setTypes("article").setQuery(
                QueryBuilders.termQuery("content", "分布式")).get();

        SearchHits hits = response.getHits();
        //2.打印出命中多少文档数据
        System.out.println(hits.getTotalHits());

        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //3.打印出实际数据
            System.out.println(sourceAsString);
        }
        //4.关闭客户端
        client.close();
    }

    /**
     * 模糊查询
     */
    @Test
    public void fuzzy() {
        //1.执行相关查询
        SearchResponse response = client.prepareSearch("blog").setTypes("article").setQuery(
                QueryBuilders.fuzzyQuery("title", "lucen")).get();

        SearchHits hits = response.getHits();
        //2.打印出命中多少文档数据
        System.out.println(hits.getTotalHits());

        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //3.打印出实际数据
            System.out.println(sourceAsString);
        }
        //4.关闭客户端
        client.close();
    }

    /**
     * 映射操作
     *
     * @throws Exception
     */
    @Test
    public void createMapping() throws Exception {

        // 1设置mapping
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                    .startObject("article")
                        .startObject("properties")
                            .startObject("id1")
                            .field("type", "string")
                            .field("store", "yes")
                            .endObject()
                            .startObject("title2")
                            .field("type", "string")
                            .field("store", "no")
                            .endObject()
                            .startObject("content")
                            .field("type", "string")
                            .field("store", "yes")
                            .endObject()
                        .endObject()
                    .endObject()
                .endObject();

        // 2 添加mapping
        PutMappingRequest mapping = Requests.putMappingRequest("blog4").type("article").source(builder);

        client.admin().indices().putMapping(mapping).get();

        // 3 关闭资源
        client.close();
    }


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章