Spring Boot Elasticsearch: 更新 store_drug_index 索引中的 isStock 值
以下是使用 Spring Boot 代码更新 Elasticsearch store_drug_index 索引中 isStock 值的示例:
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.UpdateByQueryRequest;
import org.elasticsearch.index.reindex.UpdateByQueryRequestBuilder;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
@Service
public class ElasticsearchService {
    private final RestHighLevelClient client;
    @Autowired
    public ElasticsearchService(RestHighLevelClient client) {
        this.client = client;
    }
    public void updateIsStock(String storeId, String drugId) throws IOException {
        // 构建查询条件
        TermQueryBuilder storeIdQuery = QueryBuilders.termQuery('storeId', storeId);
        TermQueryBuilder drugIdQuery = QueryBuilders.termQuery('drugId', drugId);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .must(storeIdQuery)
                .must(drugIdQuery);
        // 构建更新脚本
        Script script = new Script(ScriptType.INLINE, 'painless', "ctx._source['isStock'] = true", null);
        // 构建更新请求
        UpdateByQueryRequest updateRequest = new UpdateByQueryRequestBuilder(client)
                .source('store_drug_index')
                .filter(boolQueryBuilder)
                .script(script)
                .build();
        // 执行更新请求
        BulkByScrollResponse response = client.updateByQuery(updateRequest, RequestOptions.DEFAULT);
        // 处理更新结果
        if (response.getBulkFailures().size() > 0) {
            // 更新失败
            System.out.println('Update failed');
        } else {
            // 更新成功
            System.out.println('Update successful');
        }
    }
}
在这个示例中,ElasticsearchService 是一个使用 RestHighLevelClient 进行 Elasticsearch 操作的服务类。updateIsStock 方法接受 storeId 和 drugId 作为参数,并构建相应的查询条件和更新脚本。然后,使用 UpdateByQueryRequest 执行更新请求,并根据更新结果进行处理。
请确保在 Spring Boot 项目中正确配置 RestHighLevelClient,以便与 Elasticsearch 建立连接,并将其注入到 ElasticsearchService 类中。
原文地址: https://www.cveoy.top/t/topic/pjPY 著作权归作者所有。请勿转载和采集!