如何为带额外路径的Elasticsearch地址配置Java Rest Client的Host与Port?
Great question! When dealing with Elasticsearch endpoints that have an extra base path (like your dev environment's https://elasticsearch.eu:443/v1/elastic), you need to split the URL into two key parts for the RestClient setup: the core host/port/protocol, and the base path prefix.
Here's exactly how to set it up correctly:
Break down the dev environment URL
- Host:
elasticsearch.eu - Port:
443(standard secure port for HTTPS) - Scheme:
https(critical—RestClient defaults to HTTP, so this must be explicitly set) - Base path:
/v1/elastic(the extra path segment after the host/port)
- Host:
Build the RestClient with path prefix
Use thesetPathPrefix()method to attach that extra base path to all outgoing requests. This way, you don't have to manually append the path to every API call.// Dev environment configuration String devHost = "elasticsearch.eu"; int devPort = 443; String devScheme = "https"; String basePath = "/v1/elastic"; RestClient restClient = RestClient.builder( new HttpHost(devHost, devPort, devScheme) ) .setPathPrefix(basePath) .build();Quick comparison to your local setup
For your locallocalhost:9200(no base path), your original code works perfectly because there's no extra path to append:RestClient localRestClient = RestClient.builder( new HttpHost("localhost", 9200) // Defaults to HTTP scheme ).build();
Key Notes
- The
setPathPrefix()method handles leading slashes automatically, so you can pass either/v1/elasticorv1/elastic—but including the leading slash makes the intent clearer. - Always specify the
schemeparameter for HTTPS endpoints; omitting it will default to HTTP, which will cause connection failures to secure ports like 443.
内容的提问来源于stack exchange,提问作者Denisa Corbu

