云搜索服务目前支持 ES 7.10.2
和 OpenSearch 2.9.0
版本实例。如果由 ES 7.10.2 实例切换到 OpenSearch 2.9.0 实例,在使用 Java SDK 连接实例时,需要切换到 OpenSearch 2.9 Java SDK。本文将以将以 Java High Level REST Client 为例,介绍 SDK 的切换过程。
OpenSearch 2.9 SDK 基本兼容了 ES 7.10.2 x-pack 之外的 API,即兼容了 ES 7.10.2 OSS API。用户切换 SDK 正常只需做以下三步改动:
pom.xml
或者 Gradle build.gradle
文件。curl -k -XPOST -u <user>:<password> -H "Content-Type: application/x-ndjson" https://localhost:9200/accounts/_bulk --data-binary @accounts.json
此处主要介绍 ES 7.10.2 的 Java High Level REST Client SDK 用法。
在build.gradle
构建文件中添加 ES SDK 依赖声明。
dependencies { implementation 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.10.2' .... }
查询用法。
import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.TrustAllStrategy; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.ssl.SSLContexts; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import javax.net.ssl.SSLContext; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; public class Main { private static RestHighLevelClient client; public static void main(String[] args) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { initEsClient(); try { QueryBuilder query = QueryBuilders.matchQuery("city", "Vernon"); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder() .size(1000) .query(query); SearchRequest searchRequest = new SearchRequest() .indices("accounts") .source(sourceBuilder); SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); System.out.println(response.getHits().getHits()[0].getId()); } finally { client.close(); } } private static void initEsClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { // Ignore } }
说明
上述 Java 代码中的 Ignore 处,需要替换为初始化语句,您可以参考通过 Java 连接 ES 实例。
修改 build.gradle
构建文件中的 SDK 依赖声明,把 es sdk 替换为 opensearch 2.9 sdk。
dependencies { implementation 'org.opensearch.client:opensearch-rest-high-level-client:2.9.0' .... }
只需要修改源码文件中的 import 相关包的路径,其他地方不需要修改。
原来的 import 语句 | 修改后的 import 语句 |
---|---|
|
|