idea java操作es

<?xml version="1.0" encoding="UTF-8"?>


4.0.0

<groupId>com.xinghuan.nsj</groupId>
<artifactId>MyHbase</artifactId>
<version>1.0-SNAPSHOT</version>

<!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-client -->
<dependencies>
<dependency>
    <groupId>org.apache.hbase</groupId>
    <artifactId>hbase-client</artifactId>
    <version>1.3.5</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>6.5.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <!--这个netty连接es有用到-->
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.13.Final</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.11.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>compile</scope>
    </dependency>



</dependencies>

package com.nsj.es;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
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.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
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.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

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

public class EsDemo {
public static void main(String[] args) {
queryData();
}

public static void queryData(){
    //指定es集群 192.168.146.129   https://www.cnblogs.com/kakatadage/p/10021957.html
    Settings set=  Settings.builder().put("cluster.name","nsj-application").build();
    //创建访问ES服务器的客户端
    try {
        TransportClient client = new PreBuiltTransportClient(set)
                .addTransportAddress(
                        new TransportAddress(
                                InetAddress.getByName("192.168.146.129"),9300));

//get方式数据查询 ,参数为Index,type和id
GetResponse response = client.prepareGet(“consumer”,“employee”,“2”).get();

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

    } catch (Exception e) {
        e.printStackTrace();
    }

}


//插入数据

@Test
public void test2() throws IOException {
    //指定ES集群
    Settings setting = Settings.builder().put("cluster.name",
            "nsj-application").build();

    //创建访问ES服务器的客户端
    TransportClient client = new PreBuiltTransportClient(setting)
            .addTransportAddress(
                    new TransportAddress(
                            InetAddress.getByName("192.168.146.129"),9300));

    XContentBuilder doc = XContentFactory.jsonBuilder()
            .startObject()
            .field("id","5")
            .field("title","我在学习es插入操作")
            .field("content","好好学习,天天向上")
            .endObject();

    //添加一个doc
    IndexResponse response = client.prepareIndex("consumer","employee",null)//id为null,由ES自己生成
            .setSource(doc).get();
    System.out.println(response.status());//打印添加是否成功
    client.close();
}


//删除ES一个文档
@Test
public void delete() throws Exception{
    //指定ES集群
    Settings setting = Settings.builder().put("cluster.name",
            "nsj-application").build();

    //创建访问ES服务器的客户端
    TransportClient client = new PreBuiltTransportClient(setting)
            .addTransportAddress(
                    new TransportAddress(
                            InetAddress.getByName("hadoop2"),9300));

    DeleteResponse response = client.prepareDelete("consumer","employee","1")
            .get();
    System.out.println(response.status());//打印添加是否成功
    client.close();



}

@Test
public void update() throws IOException, ExecutionException, InterruptedException {
    //指定ES集群
    Settings setting = Settings.builder().put("cluster.name",
            "nsj-application").build();

    //创建访问ES服务器的客户端
    TransportClient client = new PreBuiltTransportClient(setting)
            .addTransportAddress(
                    new TransportAddress(
                            InetAddress.getByName("hadoop2"),9300));
    UpdateRequest request = new UpdateRequest();
    request.index("consumer")
            .type("employee")
            .id("1q7yHmwBCxDcI2VV-5Qi")
            .doc(
                    XContentFactory.jsonBuilder().startObject()
                            .field("title","我在学习ES的修改操作")
                            .field("newadd","新增字段")
                            .endObject()
            );
    UpdateResponse response = client.update(request).get();

    System.out.println(response.status());//打印是否成功
    client.close();
}


//mget批量查询
@Test
public void mget() throws Exception{
    //指定ES集群
    Settings setting = Settings.builder().put("cluster.name",
            "nsj-application").build();

    //创建访问ES服务器的客户端
    TransportClient client = new PreBuiltTransportClient(setting)
            .addTransportAddress(
                    new TransportAddress(
                            InetAddress.getByName("hadoop2"),9300));
    MultiGetResponse responses = client.prepareMultiGet()
            .add("consumer", "employee", "1", "2")
            .add("nsj", "area", "1")
            .get();
    for (MultiGetItemResponse item : responses) {
        GetResponse gr = item.getResponse();
        if (gr != null && gr.isExists()) {
            System.out.println(gr.getSourceAsString());
        }
    }
}

//bulk批量操作
@Test
public void bulk() throws IOException {
//指定ES集群
Settings setting = Settings.builder().put(“cluster.name”,
“nsj-application”).build();

    //创建访问ES服务器的客户端
    TransportClient client = new PreBuiltTransportClient(setting)
            .addTransportAddress(
                    new TransportAddress(
                            InetAddress.getByName("hadoop2"),9300));
    BulkRequestBuilder bulkBuilder = client.prepareBulk();

    //批量添加
    bulkBuilder.add(
            client.prepareIndex("lib2", "books", "8")
                    .setSource(
                            XContentFactory.jsonBuilder()
                                    .startObject()
                                    .field("title", "python")
                                    .field("price", 99)
                                    .endObject()
                    )
    );
    bulkBuilder.add(
            client.prepareIndex("lib2", "books", "9")
                    .setSource(
                            XContentFactory.jsonBuilder()
                                    .startObject()
                                    .field("title", "R")
                                    .field("price", 89)
                                    .endObject()
                    )
    );

    BulkResponse responses = bulkBuilder.get();

    System.out.println(responses.status());
}

/**
 * 查询所有
 */
@Test
public void selectAll() throws  Exception{
    //指定ES集群
    Settings setting = Settings.builder().put("cluster.name",
            "nsj-application").build();

    //创建访问ES服务器的客户端
    TransportClient client = new PreBuiltTransportClient(setting)
            .addTransportAddress(
                    new TransportAddress(
                            InetAddress.getByName("hadoop2"),9300));
    QueryBuilder gb = QueryBuilders.matchAllQuery();
    SearchResponse sr = client.prepareSearch("lib2")
            .setQuery(gb)
            .setSize(3)
            .get();
    SearchHits hits = sr.getHits();
    for (SearchHit hit : hits) {
        System.out.println(hit.getSourceAsString());
    }
}


/**
 * 删除所有
 */
@Test
public void deleteAll() throws  Exception{
    //指定ES集群
    Settings setting = Settings.builder().put("cluster.name",
            "nsj-application").build();

    //创建访问ES服务器的客户端
    TransportClient client = new PreBuiltTransportClient(setting)
            .addTransportAddress(
                    new TransportAddress(
                            InetAddress.getByName("hadoop2"),9300));
    BulkByScrollResponse response = DeleteByQueryAction.INSTANCE
            .newRequestBuilder(client)
            .filter(QueryBuilders.matchQuery("title", "R"))
            .source("lib2")
            .get();

    System.out.println(response.getDeleted());
}

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 IntelliJ IDEA 使用 Elasticsearch,你可以遵循以下几个步骤: 1. **安装插件**: 在 IDEA ,打开 Settings/Preferences(取决于你的 IDEA 版本),然后搜索 "Elasticsearch" 或 "Kotlin" 插件,因为 IDEA 需要 Kotlin 插件支持与 Elasticsearch 的交互。安装并启用这两个插件。 2. **配置连接**: - 配置 IntelliJ 的 Elasticsearch 插件:创建一个新的 `~/.IntelliJIdea/system/Elasticsearch` 文件夹,或者编辑现有文件夹的 `elasticsearch.yml` 文件,添加 Elasticsearch 的连接信息,如主机名、端口和认证凭据。 3. **创建索引**: 使用 IDEA 的 Data Grid 或 Data Editor 创建一个新的索引,或者通过 EQL (Elasticsearch Query Language) 查询来定义索引结构。可以通过菜单 "Tools" > "Database" > "Data Grid" 或 "Data Editor" 来操作。 4. **查询与分析数据**: 在代码,可以使用 IntelliJ 提供的 Kotlin 或 Java API (如 Elasticsearch DSL 或 REST API Client) 来执行查询和检索数据。在项目引入 Elasticsearch 客户端依赖,例如 `org.elasticsearch.client:elasticsearch-rest-high-level-client`,然后编写相应的查询代码。 5. **调试与监控**: IDEA 提供了集成的 Kibana 集成,可以在 IDE 内直接查看 Elasticsearch 的指标、日志和查询性能。选择 "Tools" > "Database" > "Kibana" 来启动或配置 Kibana。 6. **索引管理**: 对于索引的创建、删除、更新等操作,也可以通过插件提供的工具或直接在 Kibana 界面进行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值