use of org.opensearch.client.Request in project veilarbportefolje by navikt.
the class OpensearchTestClient method countDocuments.
@SneakyThrows
public int countDocuments() {
Request request = new Request("GET", indexName.getValue() + "/_count");
Response response = restHighLevelClient.getLowLevelClient().performRequest(request);
String entity = EntityUtils.toString(response.getEntity());
return new JSONObject(entity).getInt("count");
}
use of org.opensearch.client.Request in project OpenSearch by opensearch-project.
the class CRUDDocumentationIT method testUpdate.
@SuppressWarnings("unused")
public void testUpdate() throws Exception {
RestHighLevelClient client = highLevelClient();
{
IndexRequest indexRequest = new IndexRequest("posts").id("1").source("field", 0);
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
assertSame(RestStatus.CREATED, indexResponse.status());
Request request = new Request("POST", "/_scripts/increment-field");
request.setJsonEntity(Strings.toString(JsonXContent.contentBuilder().startObject().startObject("script").field("lang", "painless").field("source", "ctx._source.field += params.count").endObject().endObject()));
Response response = client().performRequest(request);
assertEquals(RestStatus.OK.getStatus(), response.getStatusLine().getStatusCode());
}
{
// tag::update-request
UpdateRequest request = new UpdateRequest(// <1>
"posts", // <2>
"1");
// end::update-request
request.fetchSource(true);
// tag::update-request-with-inline-script
// <1>
Map<String, Object> parameters = singletonMap("count", 4);
Script inline = new Script(ScriptType.INLINE, "painless", "ctx._source.field += params.count", // <2>
parameters);
// <3>
request.script(inline);
// end::update-request-with-inline-script
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
assertEquals(4, updateResponse.getGetResult().getSource().get("field"));
request = new UpdateRequest("posts", "1").fetchSource(true);
// tag::update-request-with-stored-script
Script stored = new Script(ScriptType.STORED, null, "increment-field", // <1>
parameters);
// <2>
request.script(stored);
// end::update-request-with-stored-script
updateResponse = client.update(request, RequestOptions.DEFAULT);
assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
assertEquals(8, updateResponse.getGetResult().getSource().get("field"));
}
{
// tag::update-request-with-doc-as-map
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("updated", new Date());
jsonMap.put("reason", "daily update");
UpdateRequest request = new UpdateRequest("posts", "1").doc(// <1>
jsonMap);
// end::update-request-with-doc-as-map
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
}
{
// tag::update-request-with-doc-as-xcontent
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.timeField("updated", new Date());
builder.field("reason", "daily update");
}
builder.endObject();
UpdateRequest request = new UpdateRequest("posts", "1").doc(// <1>
builder);
// end::update-request-with-doc-as-xcontent
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
}
{
// tag::update-request-shortcut
UpdateRequest request = new UpdateRequest("posts", "1").doc("updated", new Date(), "reason", // <1>
"daily update");
// end::update-request-shortcut
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
}
{
// tag::update-request-with-doc-as-string
UpdateRequest request = new UpdateRequest("posts", "1");
String jsonString = "{" + "\"updated\":\"2017-01-01\"," + "\"reason\":\"daily update\"" + "}";
// <1>
request.doc(jsonString, XContentType.JSON);
// end::update-request-with-doc-as-string
request.fetchSource(true);
// tag::update-execute
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
// end::update-execute
assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
// tag::update-response
String index = updateResponse.getIndex();
String id = updateResponse.getId();
long version = updateResponse.getVersion();
if (updateResponse.getResult() == DocWriteResponse.Result.CREATED) {
// <1>
} else if (updateResponse.getResult() == DocWriteResponse.Result.UPDATED) {
// <2>
} else if (updateResponse.getResult() == DocWriteResponse.Result.DELETED) {
// <3>
} else if (updateResponse.getResult() == DocWriteResponse.Result.NOOP) {
// <4>
}
// end::update-response
// tag::update-getresult
// <1>
GetResult result = updateResponse.getGetResult();
if (result.isExists()) {
// <2>
String sourceAsString = result.sourceAsString();
// <3>
Map<String, Object> sourceAsMap = result.sourceAsMap();
// <4>
byte[] sourceAsBytes = result.source();
} else {
// <5>
}
// end::update-getresult
assertNotNull(result);
assertEquals(3, result.sourceAsMap().size());
// tag::update-failure
ReplicationResponse.ShardInfo shardInfo = updateResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
// <1>
}
if (shardInfo.getFailed() > 0) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
// <2>
String reason = failure.reason();
}
}
// end::update-failure
}
{
// tag::update-docnotfound
UpdateRequest request = new UpdateRequest("posts", "does_not_exist").doc("field", "value");
try {
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
} catch (OpenSearchException e) {
if (e.status() == RestStatus.NOT_FOUND) {
// <1>
}
}
// end::update-docnotfound
}
{
// tag::update-conflict
UpdateRequest request = new UpdateRequest("posts", "1").doc("field", "value").setIfSeqNo(101L).setIfPrimaryTerm(200L);
try {
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
} catch (OpenSearchException e) {
if (e.status() == RestStatus.CONFLICT) {
// <1>
}
}
// end::update-conflict
}
{
UpdateRequest request = new UpdateRequest("posts", "1").doc("reason", "no source");
// tag::update-request-no-source
// <1>
request.fetchSource(true);
// end::update-request-no-source
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
assertNotNull(updateResponse.getGetResult());
assertEquals(3, updateResponse.getGetResult().sourceAsMap().size());
}
{
UpdateRequest request = new UpdateRequest("posts", "1").doc("reason", "source includes");
// tag::update-request-source-include
String[] includes = new String[] { "updated", "r*" };
String[] excludes = Strings.EMPTY_ARRAY;
request.fetchSource(// <1>
new FetchSourceContext(true, includes, excludes));
// end::update-request-source-include
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
Map<String, Object> sourceAsMap = updateResponse.getGetResult().sourceAsMap();
assertEquals(2, sourceAsMap.size());
assertEquals("source includes", sourceAsMap.get("reason"));
assertTrue(sourceAsMap.containsKey("updated"));
}
{
UpdateRequest request = new UpdateRequest("posts", "1").doc("reason", "source excludes");
// tag::update-request-source-exclude
String[] includes = Strings.EMPTY_ARRAY;
String[] excludes = new String[] { "updated" };
request.fetchSource(// <1>
new FetchSourceContext(true, includes, excludes));
// end::update-request-source-exclude
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
Map<String, Object> sourceAsMap = updateResponse.getGetResult().sourceAsMap();
assertEquals(2, sourceAsMap.size());
assertEquals("source excludes", sourceAsMap.get("reason"));
assertTrue(sourceAsMap.containsKey("field"));
}
{
UpdateRequest request = new UpdateRequest("posts", "id");
// tag::update-request-routing
// <1>
request.routing("routing");
// end::update-request-routing
// tag::update-request-timeout
// <1>
request.timeout(TimeValue.timeValueSeconds(1));
// <2>
request.timeout("1s");
// end::update-request-timeout
// tag::update-request-retry
// <1>
request.retryOnConflict(3);
// end::update-request-retry
// tag::update-request-refresh
// <1>
request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
// <2>
request.setRefreshPolicy("wait_for");
// end::update-request-refresh
// tag::update-request-cas
// <1>
request.setIfSeqNo(2L);
// <2>
request.setIfPrimaryTerm(1L);
// end::update-request-cas
// tag::update-request-detect-noop
// <1>
request.detectNoop(false);
// end::update-request-detect-noop
// tag::update-request-upsert
String jsonString = "{\"created\":\"2017-01-01\"}";
// <1>
request.upsert(jsonString, XContentType.JSON);
// end::update-request-upsert
// tag::update-request-scripted-upsert
// <1>
request.scriptedUpsert(true);
// end::update-request-scripted-upsert
// tag::update-request-doc-upsert
// <1>
request.docAsUpsert(true);
// end::update-request-doc-upsert
// tag::update-request-active-shards
// <1>
request.waitForActiveShards(2);
// <2>
request.waitForActiveShards(ActiveShardCount.ALL);
// end::update-request-active-shards
}
{
UpdateRequest request = new UpdateRequest("posts", "async").doc("reason", "async update").docAsUpsert(true);
ActionListener<UpdateResponse> listener;
// tag::update-execute-listener
listener = new ActionListener<UpdateResponse>() {
@Override
public void onResponse(UpdateResponse updateResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::update-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::update-execute-async
// <1>
client.updateAsync(request, RequestOptions.DEFAULT, listener);
// end::update-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
use of org.opensearch.client.Request in project OpenSearch by opensearch-project.
the class CRUDDocumentationIT method testMultiTermVectors.
// Not entirely sure if _mtermvectors belongs to CRUD, and in the absence of a better place, will have it here
public void testMultiTermVectors() throws Exception {
RestHighLevelClient client = highLevelClient();
CreateIndexRequest authorsRequest = new CreateIndexRequest("authors").mapping(XContentFactory.jsonBuilder().startObject().startObject("properties").startObject("user").field("type", "keyword").endObject().endObject().endObject());
CreateIndexResponse authorsResponse = client.indices().create(authorsRequest, RequestOptions.DEFAULT);
assertTrue(authorsResponse.isAcknowledged());
client.index(new IndexRequest("index").id("1").source("user", "foobar"), RequestOptions.DEFAULT);
client.index(new IndexRequest("index").id("2").source("user", "baz"), RequestOptions.DEFAULT);
Response refreshResponse = client().performRequest(new Request("POST", "/authors/_refresh"));
assertEquals(200, refreshResponse.getStatusLine().getStatusCode());
{
// tag::multi-term-vectors-request
// <1>
MultiTermVectorsRequest request = new MultiTermVectorsRequest();
TermVectorsRequest tvrequest1 = new TermVectorsRequest("authors", "1");
tvrequest1.setFields("user");
// <2>
request.add(tvrequest1);
XContentBuilder docBuilder = XContentFactory.jsonBuilder();
docBuilder.startObject().field("user", "guest-user").endObject();
TermVectorsRequest tvrequest2 = new TermVectorsRequest("authors", docBuilder);
// <3>
request.add(tvrequest2);
// end::multi-term-vectors-request
}
// tag::multi-term-vectors-request-template
TermVectorsRequest tvrequestTemplate = // <1>
new TermVectorsRequest("authors", "fake_id");
tvrequestTemplate.setFields("user");
String[] ids = { "1", "2" };
MultiTermVectorsRequest request = // <2>
new MultiTermVectorsRequest(ids, tvrequestTemplate);
// end::multi-term-vectors-request-template
// tag::multi-term-vectors-execute
MultiTermVectorsResponse response = client.mtermvectors(request, RequestOptions.DEFAULT);
// end::multi-term-vectors-execute
// tag::multi-term-vectors-response
List<TermVectorsResponse> tvresponseList = // <1>
response.getTermVectorsResponses();
if (tvresponseList != null) {
for (TermVectorsResponse tvresponse : tvresponseList) {
}
}
// end::multi-term-vectors-response
ActionListener<MultiTermVectorsResponse> listener;
// tag::multi-term-vectors-execute-listener
listener = new ActionListener<MultiTermVectorsResponse>() {
@Override
public void onResponse(MultiTermVectorsResponse mtvResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::multi-term-vectors-execute-listener
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::multi-term-vectors-execute-async
client.mtermvectorsAsync(request, RequestOptions.DEFAULT, // <1>
listener);
// end::multi-term-vectors-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
use of org.opensearch.client.Request in project OpenSearch by opensearch-project.
the class SnapshotClientDocumentationIT method createTestSnapshots.
private void createTestSnapshots() throws IOException {
Request createSnapshot = new Request("put", String.format(Locale.ROOT, "_snapshot/%s/%s", repositoryName, snapshotName));
createSnapshot.addParameter("wait_for_completion", "true");
createSnapshot.setJsonEntity("{\"indices\":\"" + indexName + "\"}");
Response response = highLevelClient().getLowLevelClient().performRequest(createSnapshot);
// check that the request went ok without parsing JSON here. When using the high level client, check acknowledgement instead.
assertEquals(200, response.getStatusLine().getStatusCode());
}
use of org.opensearch.client.Request in project OpenSearch by opensearch-project.
the class CreatedLocationHeaderIT method testUpsert.
public void testUpsert() throws IOException {
Request request = new Request("POST", "test/_update/1");
request.setJsonEntity("{" + "\"doc\": {\"test\": \"test\"}," + "\"doc_as_upsert\": true}");
locationTestCase(client().performRequest(request));
}
Aggregations