本文整理汇总了Java中org.elasticsearch.client.RestClient类的典型用法代码示例。如果您正苦于以下问题:Java RestClient类的具体用法?Java RestClient怎么用?Java RestClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
RestClient类属于org.elasticsearch.client包,在下文中一共展示了RestClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: setupTest
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
@Override
public void setupTest(BackendListenerContext context) throws Exception {
try {
this.index = context.getParameter(ES_INDEX);
this.bulkSize = Integer.parseInt(context.getParameter(ES_BULK_SIZE));
this.timeoutMs = JMeterUtils.getPropDefault(ES_TIMEOUT_MS, DEFAULT_TIMEOUT_MS);
this.buildNumber = (JMeterUtils.getProperty(ElasticsearchBackend.BUILD_NUMBER) != null
&& JMeterUtils.getProperty(ElasticsearchBackend.BUILD_NUMBER).trim() != "")
? Integer.parseInt(JMeterUtils.getProperty(ElasticsearchBackend.BUILD_NUMBER)) : 0;
String host = context.getParameter(ES_HOST);
int port = Integer.parseInt(context.getParameter(ES_PORT));
this.client = new RestHighLevelClient(
RestClient.builder(
new HttpHost(host, port, context.getParameter(ES_SCHEME, "http")))
.setRequestConfigCallback(requestConfigBuilder ->
requestConfigBuilder
.setConnectTimeout(5000)
.setSocketTimeout((int)timeoutMs))
.setMaxRetryTimeoutMillis(60000));
this.bulkRequest = new BulkRequest().timeout(TimeValue.timeValueMillis(timeoutMs));
super.setupTest(context);
} catch (Exception e) {
throw new IllegalStateException("Unable to setup connectivity to ES", e);
}
}
示例2: bulkIndexMember
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
private void bulkIndexMember(List<?> memList) throws Exception {
StringBuilder buf = new StringBuilder(1024);
for (Object mem : memList) {
buf.append("{\"index\": {}}");
buf.append("\n");
buf.append(Gson.toJson(mem));
buf.append("\n");
}
long startTime = System.currentTimeMillis();
RestClient client = Plugin.client;
HttpEntity entity = new NStringEntity(buf.toString(), ContentType.APPLICATION_JSON);
Response indexResponse = client.performRequest("POST", "/weike/member/_bulk",
Collections.<String, String>emptyMap(), entity);
if (LOG.isDebugEnabled()) {
LOG.debug("indexMember {}ms", System.currentTimeMillis() - startTime);
LOG.debug("indexResponse {}", indexResponse.toString());
}
}
示例3: testBuildRestClient
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
public void testBuildRestClient() throws Exception {
RemoteInfo remoteInfo = new RemoteInfo("https", "localhost", 9200, new BytesArray("ignored"), null, null, emptyMap(),
RemoteInfo.DEFAULT_SOCKET_TIMEOUT, RemoteInfo.DEFAULT_CONNECT_TIMEOUT);
long taskId = randomLong();
List<Thread> threads = synchronizedList(new ArrayList<>());
RestClient client = TransportReindexAction.buildRestClient(remoteInfo, taskId, threads);
try {
assertBusy(() -> assertThat(threads, hasSize(2)));
int i = 0;
for (Thread thread : threads) {
assertEquals("es-client-" + taskId + "-" + i, thread.getName());
i++;
}
} finally {
client.close();
}
}
示例4: sourceWithMockedClient
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
private RemoteScrollableHitSource sourceWithMockedClient(boolean mockRemoteVersion, CloseableHttpAsyncClient httpClient)
throws Exception {
HttpAsyncClientBuilder clientBuilder = mock(HttpAsyncClientBuilder.class);
when(clientBuilder.build()).thenReturn(httpClient);
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200))
.setHttpClientConfigCallback(httpClientBuilder -> clientBuilder).build();
TestRemoteScrollableHitSource hitSource = new TestRemoteScrollableHitSource(restClient) {
@Override
void lookupRemoteVersion(Consumer<Version> onVersion) {
if (mockRemoteVersion) {
onVersion.accept(Version.CURRENT);
} else {
super.lookupRemoteVersion(onVersion);
}
}
};
if (mockRemoteVersion) {
hitSource.remoteVersion = Version.CURRENT;
}
return hitSource;
}
示例5: buildShards
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
private List<Shard> buildShards(Nodes nodes, RestClient client) throws IOException {
Response response = client.performRequest("GET", "test/_stats", singletonMap("level", "shards"));
List<Object> shardStats = ObjectPath.createFromResponse(response).evaluate("indices.test.shards.0");
ArrayList<Shard> shards = new ArrayList<>();
for (Object shard : shardStats) {
final String nodeId = ObjectPath.evaluate(shard, "routing.node");
final Boolean primary = ObjectPath.evaluate(shard, "routing.primary");
final Node node = nodes.getSafe(nodeId);
final SeqNoStats seqNoStats;
if (node.getVersion().onOrAfter(Version.V_6_0_0_alpha1_UNRELEASED)) {
Integer maxSeqNo = ObjectPath.evaluate(shard, "seq_no.max_seq_no");
Integer localCheckpoint = ObjectPath.evaluate(shard, "seq_no.local_checkpoint");
Integer globalCheckpoint = ObjectPath.evaluate(shard, "seq_no.global_checkpoint");
seqNoStats = new SeqNoStats(maxSeqNo, localCheckpoint, globalCheckpoint);
} else {
seqNoStats = null;
}
shards.add(new Shard(node, primary, seqNoStats));
}
return shards;
}
示例6: readVersionsFromInfo
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
private static Version readVersionsFromInfo(RestClient restClient, int numHosts) throws IOException {
Version version = null;
for (int i = 0; i < numHosts; i++) {
//we don't really use the urls here, we rely on the client doing round-robin to touch all the nodes in the cluster
Response response = restClient.performRequest("GET", "/");
ClientYamlTestResponse restTestResponse = new ClientYamlTestResponse(response);
Object latestVersion = restTestResponse.evaluate("version.number");
if (latestVersion == null) {
throw new RuntimeException("elasticsearch version not found in the response");
}
final Version currentVersion = Version.fromString(latestVersion.toString());
if (version == null) {
version = currentVersion;
} else if (version.onOrAfter(currentVersion)) {
version = currentVersion;
}
}
return version;
}
示例7: ElasticBulkSender
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
public ElasticBulkSender(String user, String password, HttpHost... hosts) {
this.user = user;
this.password = password;
this.hosts = hosts;
this.restClient = RestClient.builder(hosts)
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
if (!Strings.isBlank(user)) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
} else {
return httpClientBuilder;
}
}
})
.build();
}
示例8: doDeactivate
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
private ReplicationResult doDeactivate(TransportContext ctx, ReplicationTransaction tx, RestClient restClient) throws ReplicationException, JSONException, IOException {
ReplicationLog log = tx.getLog();
ObjectMapper mapper = new ObjectMapper();
IndexEntry content = mapper.readValue(tx.getContent().getInputStream(), IndexEntry.class);
Response deleteResponse = restClient.performRequest(
"DELETE",
"/" + content.getIndex() + "/" + content.getType() + "/" + DigestUtils.md5Hex(content.getPath()),
Collections.<String, String>emptyMap());
LOG.debug(deleteResponse.toString());
log.info(getClass().getSimpleName() + ": Delete Call returned " + deleteResponse.getStatusLine().getStatusCode() + ": " + deleteResponse.getStatusLine().getReasonPhrase());
if (deleteResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED || deleteResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ReplicationResult.OK;
}
LOG.error("Could not delete " + content.getType() + " at " + content.getPath());
return new ReplicationResult(false, 0, "Replication failed");
}
示例9: doActivate
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
/**
* Perform the replication. All logic is covered in {@link ElasticSearchIndexContentBuilder} so we only need to transmit the JSON to ElasticSearch
*
* @param ctx
* @param tx
* @param restClient
* @return
* @throws ReplicationException
*/
private ReplicationResult doActivate(TransportContext ctx, ReplicationTransaction tx, RestClient restClient) throws ReplicationException, JSONException, IOException {
ReplicationLog log = tx.getLog();
ObjectMapper mapper = new ObjectMapper();
IndexEntry content = mapper.readValue(tx.getContent().getInputStream(), IndexEntry.class);
if (content != null) {
log.info(getClass().getSimpleName() + ": Indexing " + content.getPath());
String contentString = mapper.writeValueAsString(content.getContent());
log.debug(getClass().getSimpleName() + ": Index-Content: " + contentString);
LOG.debug("Index-Content: " + contentString);
HttpEntity entity = new NStringEntity(contentString, "UTF-8");
Response indexResponse = restClient.performRequest(
"PUT",
"/" + content.getIndex() + "/" + content.getType() + "/" + DigestUtils.md5Hex(content.getPath()),
Collections.<String, String>emptyMap(),
entity);
LOG.debug(indexResponse.toString());
log.info(getClass().getSimpleName() + ": " + indexResponse.getStatusLine().getStatusCode() + ": " + indexResponse.getStatusLine().getReasonPhrase());
if (indexResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED || indexResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ReplicationResult.OK;
}
}
LOG.error("Could not replicate");
return new ReplicationResult(false, 0, "Replication failed");
}
示例10: setUp
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
/**
* 如果es集群安装了x-pack插件则以此种方式连接集群
* 1. java客户端的方式是以tcp协议在9300端口上进行通信
* 2. http客户端的方式是以http协议在9200端口上进行通信
*/
Settings settings = Settings.builder(). put("xpack.security.user", "elastic:changeme").build();
client = new PreBuiltXPackTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
elasticsearchTemplate = new ElasticsearchTemplate(client);
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("elastic", "changeme"));
restClient = RestClient.builder(new HttpHost("localhost",9200,"http"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
}).build();
}
示例11: createInstance
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
@Override
public RestClient createInstance() throws Exception {
if (this.restClient != null) {
return this.restClient;
}
HttpHost[] addresses = new HttpHost[hosts.size()];
for (int i = 0; i < hosts.size(); i++) {
addresses[i] = HttpHost.create(hosts.get(i));
}
this.restClient = RestClient
.builder(addresses)
.setMaxRetryTimeoutMillis(ESConstants.RESTCLIENT_TIMEOUT)
.build();
// this.sniffer = Sniffer.builder(this.restClient)
// .setSniffIntervalMillis(60000).build();
return this.restClient;
}
示例12: getBackendVersion
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
static int getBackendVersion(ConnectionConfiguration connectionConfiguration) {
try (RestClient restClient = connectionConfiguration.createClient()) {
Response response = restClient.performRequest("GET", "");
JsonNode jsonNode = parseResponse(response);
int backendVersion = Integer
.parseInt(jsonNode.path("version").path("number").asText().substring(0, 1));
checkArgument((backendVersion == 2 || backendVersion == 5),
"The Elasticsearch version to connect to is %s.x. "
+ "This version of the ElasticsearchIO is only compatible with "
+ "Elasticsearch v5.x and v2.x",
backendVersion);
return backendVersion;
} catch (IOException e){
throw (new IllegalArgumentException("Cannot get Elasticsearch version"));
}
}
示例13: insertTestDocuments
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
/** Inserts the given number of test documents into Elasticsearch. */
static void insertTestDocuments(ConnectionConfiguration connectionConfiguration,
long numDocs, RestClient restClient) throws IOException {
List<String> data =
ElasticSearchIOTestUtils.createDocuments(
numDocs, ElasticSearchIOTestUtils.InjectionMode.DO_NOT_INJECT_INVALID_DOCS);
StringBuilder bulkRequest = new StringBuilder();
int i = 0;
for (String document : data) {
bulkRequest.append(String.format(
"{ \"index\" : { \"_index\" : \"%s\", \"_type\" : \"%s\", \"_id\" : \"%s\" } }%n%s%n",
connectionConfiguration.getIndex(), connectionConfiguration.getType(), i++, document));
}
String endPoint = String.format("/%s/%s/_bulk", connectionConfiguration.getIndex(),
connectionConfiguration.getType());
HttpEntity requestBody =
new NStringEntity(bulkRequest.toString(), ContentType.APPLICATION_JSON);
Response response = restClient.performRequest("POST", endPoint,
Collections.singletonMap("refresh", "true"), requestBody);
ElasticsearchIO
.checkForErrors(response, ElasticsearchIO.getBackendVersion(connectionConfiguration));
}
示例14: refreshIndexAndGetCurrentNumDocs
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
/**
* Forces a refresh of the given index to make recently inserted documents available for search.
*
* @return The number of docs in the index
*/
static long refreshIndexAndGetCurrentNumDocs(
ConnectionConfiguration connectionConfiguration, RestClient restClient) throws IOException {
long result = 0;
try {
String endPoint = String.format("/%s/_refresh", connectionConfiguration.getIndex());
restClient.performRequest("POST", endPoint);
endPoint = String.format("/%s/%s/_search", connectionConfiguration.getIndex(),
connectionConfiguration.getType());
Response response = restClient.performRequest("GET", endPoint);
JsonNode searchResult = ElasticsearchIO.parseResponse(response);
result = searchResult.path("hits").path("total").asLong();
} catch (IOException e) {
// it is fine to ignore bellow exceptions because in testWriteWithBatchSize* sometimes,
// we call upgrade before any doc have been written
// (when there are fewer docs processed than batchSize).
// In that cases index/type has not been created (created upon first doc insertion)
if (!e.getMessage().contains("index_not_found_exception")){
throw e;
}
}
return result;
}
示例15: createInstance
import org.elasticsearch.client.RestClient; //导入依赖的package包/类
@Override
protected RestClient createInstance() throws Exception {
HttpHost[] hosts = new HttpHost[hostnames.length];
for (int i = 0; i < hosts.length; i++) {
hosts[i] = HttpHost.create(hostnames[i]);
}
Header[] defaultHeaders = new Header[]{new BasicHeader(HEADER_CONTENT_TYPE_KEY, DEFAULT_HEADER_CONTENT_TYPE)};
RestClient restClient = RestClient
.builder(hosts)
.setDefaultHeaders(defaultHeaders)
.setFailureListener(loggingFailureListener)
.build();
if (enableSniffer) {
this.sniffer = Sniffer.builder(restClient).build();
}
return restClient;
}