Elasticsearch 常用 API 基本操作。


(1)ElasticSearch服务默认端口9300。
(2)Web管理平台端口9200。


1、获取Transport Client

    
    private TransportClient client;

    /** 连接 ESClient */
    @Before
    public void getClient() throws UnknownHostException {

        //1、设置连接es集群的名称
        Settings settings = Settings.builder().put("cluster.name", "my-application").build();

        //2、连接集群
        client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(
                new InetSocketTransportAddress(
                        InetAddress.getByName("bigdata02"), 9300)
        );
    }

执行若显示log4j2报错,在resources目录下创建一个文件命名为log4j2.xml并添加如下内容

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%m%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

* test 目录没有 resources,新建 resources:

    点击 test右键 ->新建directory,写resources
    右键resources->点击最下面的mark directory as的resources root


2、创建索引和删除索引


   /** 创建索引 */
    @Test
    public void createIndex_ilog() {

        //创建 ilog index
        client.admin().indices().prepareCreate("ilog").get();

        //关闭 client
        client.close();

    }

    /** 删除索引 */
    @Test
    public void deleteIndex_ilog() {

        //删除 ilog index
        client.admin().indices().prepareDelete("ilog").get();

        //关闭 client
        client.close();
    }


3、创建 document(文档-行)


3.1) 通过Map创建 document(文档-行)

  	/**
     * 通过 es 自建的一个类 XContentBuilder创建document(文档-行)
     */
    @Test
    public void insertByDocumentXContent() throws Exception{
       //1、通过es自带的帮助类,构建json类
        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .field("id","3")
                .field("title","基于Lucence开发")
                .field("content","基于Lucence开发,隐藏其复杂性,提供 restful api 接口、java api 接口。")
                .endObject();

        //2、在 ES 中创建文档
        IndexResponse indexResponse = client.prepareIndex("ilog", "introduction", "3")
                .setSource(jsonBuilder).execute().get();

        client.close();
    }

3.2) 通过Map创建 document(文档-行)

    
    /**通过Map创建 document(文档-行)*/
    @Test
    public void insertDocumentByMap() {

        //1、文档数据准备,通过 Map 创建 document(文档-行)

        HashMap<String, Object> docMap = new HashMap<>();
        docMap.put("id", "2");
        docMap.put("title", "一个高度可伸缩的开源全文搜索和分析引擎");
        docMap.put("content", "它允许你以近实时的方式快速存储、搜索、分析大量数据,将 全文检索、数据分析、分布式技术 合并在一起形成的。");

        //2、在 ES 中创建文档
        IndexResponse indexResponse = client.prepareIndex("ilog", "introduction", "2")
                .setSource(docMap).execute().actionGet();

        client.close();
    }

3.3) 通过json串创建 document(文档-行)

    /**通过json串创建 document(文档-行)*/
    @Test
    public void insertDocumentByJson() {

        //1、文档数据准备,定义json字符串

        String json = "{" + "\"id\":\"1\"," + "\"title\":\"基于Lucene的搜索服务器\","
                + "\"content\":\"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"" + "}";

        //2、在 ES 中创建文档
        IndexResponse indexResponse = client.prepareIndex("ilog", "introduction", "1")
                .setSource(json).execute().actionGet();


        //3.打印创建的返回结果
        System.out.println("index:" + indexResponse.getIndex());
        System.out.println("type:" + indexResponse.getType());
        System.out.println("id:" + indexResponse.getId());
        System.out.println("result:" + indexResponse.getResult());

        client.close();
    }

4、搜索文档数据

4.1) 单个文档

    /** 查询单个文档数据 */
    @Test
    public void getDocData() {
        GetResponse response = client.prepareGet("ilog", "introduction", "1").get();

        System.out.println(response.getSourceAsString());

        client.close();
    }

4.2) 多个文档

    /** 查询多个文档数据 */
    @Test
    public void getMultiData() {

        //1、查询多个文档
        MultiGetResponse multiResponse = client.prepareMultiGet()
                .add("ilog", "introduction", "1")
                .add("ilog", "introduction", "2", "3")
                .add("ilog", "introduction", "1")
                .get();

        //2、遍历返回的结果 增强for
        for (MultiGetItemResponse itemResponse : multiResponse) {
            GetResponse getResponse = itemResponse.getResponse();

            // 如果获取到查询结果
            if (getResponse.isExists()) {
                String sourceAsString = getResponse.getSourceAsString();
                System.out.println(sourceAsString);
            }
        }
        
        client.close();
    }

# pom文件

        <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.6.1</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.6.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.9.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/junit/junit -->

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>


版权声明:本文为qq_32783151原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。