最新elasticsearch7(一、增删改查java)

前言

之前想到网上找几个es结合spring的简单实例,但是因为es的版本众多,个别版本的差异还较大,另外es本身提供多种api,导致许多文章各种乱七八糟实例,很难找到版本匹配直接能用的。所以后面直接放弃,从官网寻找方案,这里我使用elasticsearch最新的7.5版本来做样例,这里特别写一下官方文档的使用,方便小伙伴遇到问题可以自行查找。

文档使用

  • 进入官方文档 ,选择Elasticsearch:Store,Search,and Analyze下面的Elasticsearch Clients (这个就是客户端api文档)
    在这里插入图片描述
  • 我们使用java rest风格api,大家可以更加自己的版本选择特定的other versions。
    在这里插入图片描述
  • rest又分为high level和low level,我们直接选择high level下面的Getting started,Maven Repository
    在这里插入图片描述
  • maven
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.5.1</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.5.1</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>7.5.1</version>
</dependency>
  • 之后在Initialization 中我们看到需要构建RestHighLevelClient对象

spring配置

  • 在properties文件中配置es的urls:spring.elasticsearch.rest.uris=http://192.168.9.226:9200

  • 客户端调用就只需再注入client了

    @Autowired
    private RestHighLevelClient highLevelClient;

CRUD

    public void index() throws IOException {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("user", "kimchy");
        jsonMap.put("postDate", new Date());
        jsonMap.put("message", "trying out Elasticsearch");
        IndexRequest indexRequest = new IndexRequest("posts")
            .id("1").source(jsonMap);
        IndexResponse indexResponse = highLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    }
  • 删除
	public void delete(String indexName, String id) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(indexName, id);
        highLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
    }
  • 修改
	# 修改也可以通过index存在则替换或者upsets
    public void update() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("ttl", "doc", "1")
        	.script(new Script("ctx._source.gender = \"male\""));
        highLevelClient.update(updateRequest,RequestOptions.DEFAULT).getGetResult();
    }
  • 查询
	public void getIndex(String indexName, String id) throws IOException {
        GetRequest getRequest = new GetRequest(indexName, id);
        GetResponse getResponse = highLevelClient.get(getRequest, RequestOptions.DEFAULT);
        return;
    }

这篇其实主要介绍了ES官方文档的使用,当知道怎么使用官方文档后,就能轻松找到各种api及其使用方法了,减少没必要的bug出现。而且我们很多需求也只有通过官网才能实现,比如下篇将介绍的批量插入,存在即更新的操作,等同于mysql的唯一索引功能。

发布了62 篇原创文章 · 获赞 33 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/yyoc97/article/details/104167760