已删除用户
发布于 2023-10-26 / 0 阅读 / 0 评论 / 0 点赞

ES8 常用API示例

在Es7.15版本之后,es官方将它的高级客户端RestHighLevelClient标记为弃用状态。同时推出了全新的java API客户端Elasticsearch Java API Client,该客户端也将在Elasticsearch8.0及以后版本中成为官方推荐使用的客户端。

Elasticsearch Java API Client支持除Vector title search API和Find structure API之外的所有Elasticsearch API。且支持所有API数据类型,并且不再有原始JSON Value属性。它是针对Elasticsearch8.0及之后版本的客户端。

maven中引入依赖

        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.1.0</version>
        </dependency>
         <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.1</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
            <scope>provided</scope>
        </dependency>

创建连接

@Configuration
public class ElasticSearchConfig {

    /**
     * 协议
     */
    @Value("${elasticsearch.schema:http}")
    private String schema;

    @Value("${elasticsearch.address}")
    private String address;

    @Value("${elasticsearch.port}")
    Integer port;

    @Bean
    public ElasticsearchClient esRestClientWithCred() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        // 配置连接ES的用户名和密码,如果没有用户名和密码可以不加这一行
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("", ""));
        RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(address, port, schema))
            .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                @Override
                public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                    return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                }
            });
        RestClient restClient = restClientBuilder.build();
        ElasticsearchTransport transport = new RestClientTransport(
            restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        return client;
    }
}

文章Article实体类

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Article implements Serializable {
    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column articles.id
     *
     * @mbg.generated
     */
    @TableId(type = IdType.AUTO)
    private Long id;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column articles.domain_id
     *
     * @mbg.generated
     */
    private Long domainId;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column articles.title
     *
     * @mbg.generated
     */
    private String title;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column articles.link
     *
     * @mbg.generated
     */
    private String link;


    private Integer status;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column articles.create_time
     *
     * @mbg.generated
     */
    private Date createTime;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column articles.update_time
     *
     * @mbg.generated
     */
    private Date updateTime;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column articles.del_flag
     *
     * @mbg.generated
     */
    private Integer delFlag;

    private String url;

    private String salt;

    private String fileName;

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table articles
     *
     * @mbg.generated
     */
    private static final long serialVersionUID = 1L;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column articles.id
     *
     * @return the value of articles.id
     * @mbg.generated
     */
    public Long getId() {
        return id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column articles.id
     *
     * @param id the value for articles.id
     * @mbg.generated
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column articles.domain_id
     *
     * @return the value of articles.domain_id
     * @mbg.generated
     */
    public Long getDomainId() {
        return domainId;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column articles.domain_id
     *
     * @param domainId the value for articles.domain_id
     * @mbg.generated
     */
    public void setDomainId(Long domainId) {
        this.domainId = domainId;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column articles.title
     *
     * @return the value of articles.title
     * @mbg.generated
     */
    public String getTitle() {
        return title;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column articles.title
     *
     * @param title the value for articles.title
     * @mbg.generated
     */
    public void setTitle(String title) {
        this.title = title == null ? null : title.trim();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column articles.link
     *
     * @return the value of articles.link
     * @mbg.generated
     */
    public String getLink() {
        return link;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column articles.link
     *
     * @param link the value for articles.link
     * @mbg.generated
     */
    public void setLink(String link) {
        this.link = link == null ? null : link.trim();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column articles.create_time
     *
     * @return the value of articles.create_time
     * @mbg.generated
     */
    public Date getCreateTime() {
        return createTime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column articles.create_time
     *
     * @param createTime the value for articles.create_time
     * @mbg.generated
     */
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column articles.update_time
     *
     * @return the value of articles.update_time
     * @mbg.generated
     */
    public Date getUpdateTime() {
        return updateTime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column articles.update_time
     *
     * @param updateTime the value for articles.update_time
     * @mbg.generated
     */
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column articles.del_flag
     *
     * @return the value of articles.del_flag
     * @mbg.generated
     */
    public Integer getDelFlag() {
        return delFlag;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column articles.del_flag
     *
     * @param delFlag the value for articles.del_flag
     * @mbg.generated
     */
    public void setDelFlag(Integer delFlag) {
        this.delFlag = delFlag;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}

添加Aticle文档

public boolean addArticleDocument(Article article) throws IOException {
        if (Objects.isNull(article)) {
            return false;
        }

        IndexResponse response = client.index(a -> a
                .index(ARTICLE_INDEX)
                .id(article.getId().toString())
                .document(article));
        // 获取建立索引的状态信息 CREATED
        System.out.println("[add Article document]" + response.result() + ", " + response.id());
        if (Objects.equals(Result.Created, response.result())) {
            return true;
        }
        return false;
    }

更新Article文档

public boolean updateArticleDocument(Article article) throws IOException {
        if (Objects.isNull(article)) {
            return false;
        }
        UpdateResponse response = client.update(u -> u
                        .index(ARTICLE_INDEX)
                        .id(String.valueOf(article.getId()))
                        .doc(article),
                Article.class
        );
        // 获取建立索引的状态信息 Updated
        System.out.println("[update Article document]" + response.result() + ", " + response.id());
        if (Objects.equals(Result.Updated, response.result())) {
            return true;
        }
        return false;
    }

删除Article文档

public boolean deleteArticleDocument(String id) throws IOException {
        DeleteResponse deleteResponse = client.delete(d -> d
                .index(ARTICLE_INDEX)
                .id(id)
        );

        System.out.println("=====[delete] delete article document response: " + deleteResponse.result());
        if (Objects.equals(Result.Deleted, deleteResponse.result())) {
            return true;
        }
        return false;
    }

分页查询Article文档

 public PageInfo<Article> pageArticleDocuments(ArticleQueryParam queryParam) throws Exception {
        if (Objects.isNull(queryParam) || Objects.isNull(queryParam.getDomainId())
                || Objects.isNull(queryParam.getTitle())) {
            throw new Exception(ResultCode.PARAMETER_ILLEGAL.getMsg());
        }
        Integer pageNum = Objects.isNull(queryParam.getPageNum()) || queryParam.getPageNum() <= 0 ? 1
                : queryParam.getPageNum();
        Integer pageSize = Objects.isNull(queryParam.getPageSize()) || queryParam.getPageSize() <= 0 ? 10
                : queryParam.getPageSize();


        SearchResponse<Article> termSearch = client.search(s -> s
                        .index(ARTICLE_INDEX)
                        .query(q -> q
                                .bool(b -> b
                                        .must(m -> m
                                                .wildcard(t -> t
                                                        .field("title")
                                                        .value(getWildCardQueryValue(queryParam.getTitle()))
                                                )
                                        )
                                        .must(m -> m
                                                .wildcard(t -> t
                                                        .field("domainId")
                                                        .value(getWildCardQueryValue(queryParam.getDomainId()))
                                                )
                                        )
                                        .must(m -> m
                                                .term(t -> t
                                                        .field("delFlag")
                                                        .value(0)
                                                )
                                        )
                                )
                        )
                        .sort(sr -> sr
                                .field(f -> f
                                        .field("updateTime")
                                        .order(SortOrder.Desc)
                                )
                        )
                        .from(pageNum)
                        .size(pageSize)
                , Article.class);

        System.out.println("======hit total: " + termSearch.hits().total().value());
        List<Article> articles = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(termSearch.hits().hits())) {
            articles = termSearch.hits().hits().stream().map(Hit::source).collect(Collectors.toList());
        }
     
        PageInfo<Article> result = new PageInfo<>(articles);
        result.setPageNum(pageNum);
        result.setPageSize(pageSize);
        result.setTotal(termSearch.hits().total().value());
        return result;
    }


评论