Java API 基础操作ES


Elasticsearch 软件是由 Java 语言开发的,所以也可以通过 Java API 的方式对Elasticsearch服务进行访问

1、 创建 Maven 项目

我们在 IDEA 开发工具中创建 Maven 项目(模块也可)ES
在这里插入图片描述
在这里插入图片描述
修改父项目的 pom 文件,增加 Maven 依赖关系

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <elasticsearch.version>7.12.0</elasticsearch.version>
        <log4j.version>2.14.1</log4j.version>
        <jackson.verdion>2.13.0</jackson.verdion>
        <junit.version>4.13.2</junit.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <!-- elasticsearch 的客户端 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <!-- elasticsearch 依赖 2.x 的 log4j -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.verdion}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <!--<scope>test</scope>-->
        </dependency>
    </dependencies>

在这里插入图片描述

2、客户端对象

创建 com.atguigu.es.test.Elasticsearch01_Client 类,代码中创建 Elasticsearch 客户端对象因为早期版本的客户端对象已经不再推荐使用,且在未来版本中会被删除,所以这里我们采用高级 REST 客户端对象
在这里插入图片描述

public static void main(String[] args) {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        //...
        // 关闭客户端连接
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

注意9200 端口为 Elasticsearch 的 Web 通信端口localhost 为启动 ES 服务的主机名

3、索引操作

1、创建索引

	public class CreateIndex {
	    public static void main(String[] args) {
	        // 创建客户端对象
	        RestHighLevelClient client = new RestHighLevelClient(
	                RestClient.builder(new HttpHost("localhost", 9200, "http"))
	        );
	        // 创建索引- 请求对象
	        CreateIndexRequest request = new CreateIndexRequest("user");
	        // 发送请求,获取响应
	        try {
	            CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
	            //响应状态
	            boolean acknowledged = response.isAcknowledged();
	            System.out.println("操作状态 = "+acknowledged);
	            // 关闭客户端连接
	            client.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	}

操作结果:
在这里插入图片描述

2、查看索引

public class CatIndex {
    public static void main(String[] args) {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        //查询索引-请求对象
        GetIndexRequest request = new GetIndexRequest("user");
        // 发送请求,获取响应
        try {
            GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
            System.out.println("aliases:" + response.getAliases());
            System.out.println("mapping:" + response.getMappings());
            System.out.println("setting:" + response.getSettings());
            //关闭客户端
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

操作结果:
在这里插入图片描述

3、删除索引

public class DeleteIndex {
    public static void main(String[] args) {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 删除索引-请求对象
        DeleteIndexRequest request = new DeleteIndexRequest("user");
        // 发送请求,获取响应
        try {
            AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
            // 操作结果
            System.out.println("操作结果:" + response.isAcknowledged());
            // 关闭客户端
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

操作结果:
在这里插入图片描述

4、文档操作

1、新增文档

创建数据模型

public class User {
    private String name;
    private Integer age;
    private String sex;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

创建数据,添加到文档中

public class AddDoc {
    public static void main(String[] args) {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 新增文档-请求对象
        IndexRequest request = new IndexRequest();
        // 设置索引及唯一标识
        request.index("user").id("1001");
        //创建数据对象
        User user = new User();
        user.setName("祝八一");
        user.setAge(22);
        user.setSex("男");
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String productJSON = objectMapper.writeValueAsString(user);
            // 添加文档数据,数据格式为JSON格式
            request.source(productJSON, XContentType.JSON);
            //客户端发送请求,获取响应对象
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            //打印结果
            System.out.println("_index:"+response.getIndex());
            System.out.println("_id:"+response.getId());
            System.out.println("_result:"+response.getResult());
            //关闭客户端
            client.close();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}

操作结果:
在这里插入图片描述

2、修改文档

public class UpdateDoc {
    public static void main(String[] args) {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 修改文档-请求对象
        UpdateRequest request = new UpdateRequest();
        //配置修改参数
        request.index("user").id("1001");
        //设置请求体,对数据进行修改
        request.doc(XContentType.JSON,"sex","女");
        //客户端发送请求,获取响应对象
        try {
            UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
            //打印结果
            System.out.println("_index:"+response.getIndex());
            System.out.println("_id:"+response.getId());
            System.out.println("_result:"+response.getResult());
            //关闭客户端
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

操作结果:
在这里插入图片描述

3、 查询文档

public class QueryDoc {
    public static void main(String[] args) {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 创建请求对象
        GetRequest request = new GetRequest().index("user").id("1001");
        try {
            // 客户端发送请求,获取响应对象
            GetResponse response = client.get(request, RequestOptions.DEFAULT);
            //打印结果
            System.out.println("_index:"+response.getIndex());
            System.out.println("_type:"+response.getType());
            System.out.println("_id:"+response.getId());
            System.out.println("source:"+response.getSourceAsString());
            //关闭客户端
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

执行结果为:
在这里插入图片描述

4、删除文档

public class DeleteDoc {
    public static void main(String[] args) {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 创建删除请求
        DeleteRequest request = new DeleteRequest().index("user").id("1001");
        //发送请求,获取响应
        try {
            DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
            //打印信息
            System.out.println(response.toString());
            //关闭客户端
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

执行结果为:
在这里插入图片描述

5、批量操作

  • 批量新增:
/**
 * @author zhubayi
 * 批量新增
 */
public class BulkAddDoc {
    public static void main(String[] args) {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        //创建批量新增请求
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON,"name","zhangsan"));
        request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON,"name","lisi"));
        request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON,"name","wangwu"));
        try {
            //客户端发送请求,获取响应对象
            BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
            //打印结果信息
            System.out.println("took:"+responses.getTook());
            System.out.println("items:"+responses.getItems());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭客户端
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

执行结果为:
在这里插入图片描述

  • 批量删除:
/**
 * @author zhubayi
 * 批量删除
 */
public class BulkDeleteDoc {
    public static void main(String[] args) {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        //创建批量删除的请求
        BulkRequest request = new BulkRequest();
        request.add(new DeleteRequest().index("user").id("1001"));
        request.add(new DeleteRequest().index("user").id("1002"));
        request.add(new DeleteRequest().index("user").id("1003"));
        //客户端发送请求,获取响应对象
        BulkResponse responses = null;
        try {
            responses = client.bulk(request, RequestOptions.DEFAULT);
            //打印结果信息
            System.out.println("took:" + responses.getTook());
            System.out.println("items:" + responses.getItems());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭客户端
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

执行结果为:
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java API可以用于操作ElasticsearchES)搜索引擎,以下是使用Java API进行ES操作的基本步骤: 1. 导入依赖 在项目中添加Elasticsearch Java API的依赖,例如: ```xml <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.14.1</version> </dependency> ``` 2. 创建连接 使用Java API连接ES集群,例如: ```java RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http"))); ``` 3. 创建索引 使用Java API创建索引,例如: ```java CreateIndexRequest request = new CreateIndexRequest("my_index"); client.indices().create(request, RequestOptions.DEFAULT); ``` 4. 添加文档 使用Java API向索引添加文档,例如: ```java IndexRequest request = new IndexRequest("my_index"); request.id("1"); String jsonString = "{" + "\"name\":\"John\"," + "\"age\":30," + "\"city\":\"New York\"" + "}"; request.source(jsonString, XContentType.JSON); client.index(request, RequestOptions.DEFAULT); ``` 5. 搜索文档 使用Java API搜索文档,例如: ```java SearchRequest request = new SearchRequest("my_index"); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchQuery("name", "John")); request.source(builder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); ``` 6. 关闭连接 使用完Java API后,需要关闭连接,例如: ```java client.close(); ``` 以上就是使用Java API操作ES的基本步骤。具体的操作方式和方法需要根据具体的需求来进行选择。同时,需要注意ES版本和Java API版本的兼容性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值