Search in sources :

Example 1 with SearchResponse

use of org.opensearch.client.opensearch.core.SearchResponse in project opensearch-java by opensearch-project.

the class RequestTest method testDataIngestion.

@Test
public void testDataIngestion() throws Exception {
    String index = "ingest-test";
    // Create an index
    CreateIndexResponse createIndexResponse = highLevelClient().indices().create(b -> b.index(index));
    assertEquals(index, createIndexResponse.index());
    // Check that it actually exists. Example of a boolean response
    BooleanResponse existsResponse = highLevelClient().indices().exists(b -> b.index(index));
    assertTrue(existsResponse.value());
    // Ingest some data
    AppData appData = new AppData();
    appData.setIntValue(1337);
    appData.setMsg("foo");
    String docId = highLevelClient().index(b -> b.index(index).id(// test with url-unsafe string
    "my/Id").document(appData).refresh(// Make it visible for search
    Refresh.True)).id();
    assertEquals("my/Id", docId);
    // Check auto-created mapping
    GetMappingResponse mapping = highLevelClient().indices().getMapping(b -> b.index(index));
    assertEquals(Property.Kind.Long, mapping.get("ingest-test").mappings().properties().get("intValue")._kind());
    // Query by id
    AppData esData = highLevelClient().get(b -> b.index(index).id(docId), AppData.class).source();
    assertEquals(1337, esData.getIntValue());
    assertEquals("foo", esData.getMsg());
    // Query by id a non-existing document
    final GetResponse<AppData> notExists = highLevelClient().get(b -> b.index(index).id("some-random-id"), AppData.class);
    assertFalse(notExists.found());
    assertNull(notExists.source());
    // Search
    SearchResponse<AppData> search = highLevelClient().search(b -> b.index(index), AppData.class);
    long hits = search.hits().total().value();
    assertEquals(1, hits);
    esData = search.hits().hits().get(0).source();
    assertEquals(1337, esData.getIntValue());
    assertEquals("foo", esData.getMsg());
    RequestItem item = RequestItem.of(_1 -> _1.header(_2 -> _2.index("test")).body(_2 -> _2.size(4)));
    // MSearch: 1st search on an existing index, 2nd one on a non-existing index
    final MsearchResponse<AppData> msearch = highLevelClient().msearch(_0 -> _0.searches(_1 -> _1.header(_3 -> _3.index(index)).body(_3 -> _3.query(_4 -> _4.matchAll(_5 -> _5)))).searches(_1 -> _1.header(_3 -> _3.index("non-existing")).body(_3 -> _3.query(_4 -> _4.matchAll(_5 -> _5)))), AppData.class);
    assertEquals(2, msearch.responses().size());
    assertTrue(msearch.responses().get(0).isResult());
    assertEquals(1, msearch.responses().get(0).result().hits().hits().size());
    assertTrue(msearch.responses().get(1).isFailure());
    assertEquals(404, msearch.responses().get(1).failure().status());
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) CreateIndexResponse(org.opensearch.client.opensearch.indices.CreateIndexResponse) GetMappingResponse(org.opensearch.client.opensearch.indices.GetMappingResponse) HistogramAggregate(org.opensearch.client.opensearch._types.aggregations.HistogramAggregate) OperationType(org.opensearch.client.opensearch.core.bulk.OperationType) Property(org.opensearch.client.opensearch._types.mapping.Property) IndexResponse(org.opensearch.client.opensearch.core.IndexResponse) Map(java.util.Map) Refresh(org.opensearch.client.opensearch._types.Refresh) GetIndexResponse(org.opensearch.client.opensearch.indices.GetIndexResponse) OpenSearchAsyncClient(org.opensearch.client.opensearch.OpenSearchAsyncClient) BooleanResponse(org.opensearch.client.transport.endpoints.BooleanResponse) RequestItem(org.opensearch.client.opensearch.core.msearch.RequestItem) OpenSearchException(org.opensearch.client.opensearch._types.OpenSearchException) IndexState(org.opensearch.client.opensearch.indices.IndexState) Test(org.junit.Test) IOException(java.io.IOException) BulkResponse(org.opensearch.client.opensearch.core.BulkResponse) SearchResponse(org.opensearch.client.opensearch.core.SearchResponse) ClearScrollResponse(org.opensearch.client.opensearch.core.ClearScrollResponse) MsearchResponse(org.opensearch.client.opensearch.core.MsearchResponse) GetIndicesSettingsResponse(org.opensearch.client.opensearch.indices.GetIndicesSettingsResponse) ModelTestCase(org.opensearch.client.opensearch.model.ModelTestCase) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) NodesResponse(org.opensearch.client.opensearch.cat.NodesResponse) GetResponse(org.opensearch.client.opensearch.core.GetResponse) Collections(java.util.Collections) RequestItem(org.opensearch.client.opensearch.core.msearch.RequestItem) GetMappingResponse(org.opensearch.client.opensearch.indices.GetMappingResponse) CreateIndexResponse(org.opensearch.client.opensearch.indices.CreateIndexResponse) BooleanResponse(org.opensearch.client.transport.endpoints.BooleanResponse) Test(org.junit.Test)

Example 2 with SearchResponse

use of org.opensearch.client.opensearch.core.SearchResponse in project opensearch-java by opensearch-project.

the class RequestTest method testSearchAggregation.

@Test
public void testSearchAggregation() throws IOException {
    highLevelClient().create(_1 -> _1.index("products").id("A").document(new Product(5)).refresh(Refresh.True));
    highLevelClient().create(_1 -> _1.index("products").id("B").document(new Product(15)).refresh(Refresh.True));
    highLevelClient().create(_1 -> _1.index("products").id("C").document(new Product(25)).refresh(Refresh.True));
    SearchResponse<Product> searchResponse = highLevelClient().search(_1 -> _1.index("products").size(0).aggregations("prices", _3 -> _3.histogram(_4 -> _4.field("price").interval(10.0)).aggregations("average", _5 -> _5.avg(_6 -> _6.field("price")))), Product.class);
    HistogramAggregate prices = searchResponse.aggregations().get("prices").histogram();
    assertEquals(3, prices.buckets().array().size());
    assertEquals(1, prices.buckets().array().get(0).docCount());
    assertEquals(5.0, prices.buckets().array().get(0).aggregations().get("average").avg().value(), 0.01);
    // We've set "size" to zero
    assertEquals(0, searchResponse.hits().hits().size());
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) CreateIndexResponse(org.opensearch.client.opensearch.indices.CreateIndexResponse) GetMappingResponse(org.opensearch.client.opensearch.indices.GetMappingResponse) HistogramAggregate(org.opensearch.client.opensearch._types.aggregations.HistogramAggregate) OperationType(org.opensearch.client.opensearch.core.bulk.OperationType) Property(org.opensearch.client.opensearch._types.mapping.Property) IndexResponse(org.opensearch.client.opensearch.core.IndexResponse) Map(java.util.Map) Refresh(org.opensearch.client.opensearch._types.Refresh) GetIndexResponse(org.opensearch.client.opensearch.indices.GetIndexResponse) OpenSearchAsyncClient(org.opensearch.client.opensearch.OpenSearchAsyncClient) BooleanResponse(org.opensearch.client.transport.endpoints.BooleanResponse) RequestItem(org.opensearch.client.opensearch.core.msearch.RequestItem) OpenSearchException(org.opensearch.client.opensearch._types.OpenSearchException) IndexState(org.opensearch.client.opensearch.indices.IndexState) Test(org.junit.Test) IOException(java.io.IOException) BulkResponse(org.opensearch.client.opensearch.core.BulkResponse) SearchResponse(org.opensearch.client.opensearch.core.SearchResponse) ClearScrollResponse(org.opensearch.client.opensearch.core.ClearScrollResponse) MsearchResponse(org.opensearch.client.opensearch.core.MsearchResponse) GetIndicesSettingsResponse(org.opensearch.client.opensearch.indices.GetIndicesSettingsResponse) ModelTestCase(org.opensearch.client.opensearch.model.ModelTestCase) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) NodesResponse(org.opensearch.client.opensearch.cat.NodesResponse) GetResponse(org.opensearch.client.opensearch.core.GetResponse) Collections(java.util.Collections) HistogramAggregate(org.opensearch.client.opensearch._types.aggregations.HistogramAggregate) Test(org.junit.Test)

Example 3 with SearchResponse

use of org.opensearch.client.opensearch.core.SearchResponse in project opensearch-java by opensearch-project.

the class TypedKeysTest method testAdditionalProperties.

@Test
public void testAdditionalProperties() {
    Aggregate avg1 = AvgAggregate.of(_1 -> _1.value(1.0))._toAggregate();
    Aggregate avg2 = AvgAggregate.of(_1 -> _1.value(2.0))._toAggregate();
    Aggregate aggregate = StringTermsAggregate.of(_0 -> _0.sumOtherDocCount(1).buckets(b -> b.array(ListBuilder.of(StringTermsBucket.Builder::new).add(_1 -> _1.key("key_1").docCount(1).aggregations(MapBuilder.of("bar", avg1))).add(_1 -> _1.key("key_2").docCount(2).aggregations(MapBuilder.of("bar", avg2))).build())))._toAggregate();
    SearchResponse<Void> resp = new SearchResponse.Builder<Void>().aggregations("foo", aggregate).took(1).shards(_1 -> _1.successful(1).failed(0).total(1)).hits(_1 -> _1.total(_2 -> _2.value(0).relation(TotalHitsRelation.Eq)).hits(Collections.emptyList())).timedOut(false).build();
    String json = "{\"took\":1,\"timed_out\":false,\"_shards\":{\"failed\":0.0,\"successful\":1.0,\"total\":1.0}," + "\"hits\":{\"total\":{\"relation\":\"eq\",\"value\":0},\"hits\":[]}," + "\"aggregations\":{\"sterms#foo\":{\"buckets\":[" + "{\"avg#bar\":{\"value\":1.0},\"doc_count\":1,\"key\":\"key_1\"}," + "{\"avg#bar\":{\"value\":2.0},\"doc_count\":2,\"key\":\"key_2\"}" + "],\"sum_other_doc_count\":1}}}";
    assertEquals(json, toJson(resp));
    resp = fromJson(json, SearchResponse.createSearchResponseDeserializer(JsonpDeserializer.voidDeserializer()));
    StringTermsAggregate foo = resp.aggregations().get("foo").sterms();
    assertEquals(1, foo.sumOtherDocCount());
    assertEquals(1, foo.buckets().array().get(0).docCount());
    assertEquals("key_1", foo.buckets().array().get(0).key());
    assertEquals(1.0, foo.buckets().array().get(0).aggregations().get("bar").avg().value(), 0.01);
    assertEquals("key_2", foo.buckets().array().get(1).key());
    assertEquals(2.0, foo.buckets().array().get(1).aggregations().get("bar").avg().value(), 0.01);
}
Also used : StringTermsAggregate(org.opensearch.client.opensearch._types.aggregations.StringTermsAggregate) TotalHitsRelation(org.opensearch.client.opensearch.core.search.TotalHitsRelation) JsonpDeserializer(org.opensearch.client.json.JsonpDeserializer) ListBuilder(org.opensearch.client.util.ListBuilder) MapBuilder(org.opensearch.client.util.MapBuilder) Test(org.junit.Test) Aggregate(org.opensearch.client.opensearch._types.aggregations.Aggregate) AvgAggregate(org.opensearch.client.opensearch._types.aggregations.AvgAggregate) SearchResponse(org.opensearch.client.opensearch.core.SearchResponse) Collections(java.util.Collections) StringTermsBucket(org.opensearch.client.opensearch._types.aggregations.StringTermsBucket) StringTermsAggregate(org.opensearch.client.opensearch._types.aggregations.StringTermsAggregate) ListBuilder(org.opensearch.client.util.ListBuilder) MapBuilder(org.opensearch.client.util.MapBuilder) StringTermsBucket(org.opensearch.client.opensearch._types.aggregations.StringTermsBucket) StringTermsAggregate(org.opensearch.client.opensearch._types.aggregations.StringTermsAggregate) Aggregate(org.opensearch.client.opensearch._types.aggregations.Aggregate) AvgAggregate(org.opensearch.client.opensearch._types.aggregations.AvgAggregate) Test(org.junit.Test)

Example 4 with SearchResponse

use of org.opensearch.client.opensearch.core.SearchResponse in project opensearch-java by opensearch-project.

the class ApiConventionsTest method builderIntervals.

@Test(expected = TransportException.class)
public void builderIntervals() throws Exception {
    OpenSearchClient client = new OpenSearchClient(transport);
    // tag::builder-intervals
    SearchResponse<SomeApplicationData> results = client.search(_0 -> _0.query(_1 -> _1.intervals(_2 -> _2.field("my_text").allOf(_3 -> _3.ordered(true).intervals(_4 -> _4.match(_5 -> _5.query("my favorite food").maxGaps(0).ordered(true))).intervals(_4 -> _4.anyOf(_5 -> _5.intervals(_6 -> _6.match(_7 -> _7.query("hot water"))).intervals(_6 -> _6.match(_7 -> _7.query("cold porridge")))))))), // <1>
    SomeApplicationData.class);
// end::builder-intervals
}
Also used : OpenSearchAsyncClient(org.opensearch.client.opensearch.OpenSearchAsyncClient) Arrays(java.util.Arrays) Aggregation(org.opensearch.client.opensearch._types.aggregations.Aggregation) Alias(org.opensearch.client.opensearch.indices.Alias) Query(org.opensearch.client.opensearch._types.query_dsl.Query) CreateIndexRequest(org.opensearch.client.opensearch.indices.CreateIndexRequest) LogManager(java.util.logging.LogManager) OpenSearchClient(org.opensearch.client.opensearch.OpenSearchClient) Test(org.junit.Test) HashMap(java.util.HashMap) CreateIndexResponse(org.opensearch.client.opensearch.indices.CreateIndexResponse) Logger(java.util.logging.Logger) SearchResponse(org.opensearch.client.opensearch.core.SearchResponse) OpenSearchTransport(org.opensearch.client.transport.OpenSearchTransport) TransportException(org.opensearch.client.transport.TransportException) List(java.util.List) SearchRequest(org.opensearch.client.opensearch.core.SearchRequest) NodeStatistics(org.opensearch.client.opensearch._types.NodeStatistics) SortOrder(org.opensearch.client.opensearch._types.SortOrder) ApiTypeHelper(org.opensearch.client.util.ApiTypeHelper) Map(java.util.Map) Assert(org.junit.Assert) OpenSearchClient(org.opensearch.client.opensearch.OpenSearchClient) Test(org.junit.Test)

Example 5 with SearchResponse

use of org.opensearch.client.opensearch.core.SearchResponse in project opensearch-java by opensearch-project.

the class ConnectingTest method createClient.

// we don't have a running ES
@Ignore
@Test
public void createClient() throws Exception {
    // tag::create-client
    // Create the low-level client
    RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
    // Create the transport with a Jackson mapper
    OpenSearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    // And create the API client
    OpenSearchClient client = new OpenSearchClient(transport);
    // end::create-client
    // tag::first-request
    SearchResponse<Product> search = client.search(s -> s.index("products").query(q -> q.term(t -> t.field("name").value(v -> v.stringValue("bicycle")))), Product.class);
    for (Hit<Product> hit : search.hits().hits()) {
        processProduct(hit.source());
    }
// end::first-request
}
Also used : JacksonJsonpMapper(org.opensearch.client.json.jackson.JacksonJsonpMapper) Ignore(org.junit.Ignore) RestClientTransport(org.opensearch.client.transport.rest_client.RestClientTransport) RestClient(org.opensearch.client.RestClient) OpenSearchClient(org.opensearch.client.opensearch.OpenSearchClient) Test(org.junit.Test) SearchResponse(org.opensearch.client.opensearch.core.SearchResponse) HttpHost(org.apache.http.HttpHost) Hit(org.opensearch.client.opensearch.core.search.Hit) OpenSearchTransport(org.opensearch.client.transport.OpenSearchTransport) RestClientTransport(org.opensearch.client.transport.rest_client.RestClientTransport) HttpHost(org.apache.http.HttpHost) RestClient(org.opensearch.client.RestClient) JacksonJsonpMapper(org.opensearch.client.json.jackson.JacksonJsonpMapper) OpenSearchClient(org.opensearch.client.opensearch.OpenSearchClient) OpenSearchTransport(org.opensearch.client.transport.OpenSearchTransport) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)5 SearchResponse (org.opensearch.client.opensearch.core.SearchResponse)5 Collections (java.util.Collections)3 Map (java.util.Map)3 OpenSearchAsyncClient (org.opensearch.client.opensearch.OpenSearchAsyncClient)3 CreateIndexResponse (org.opensearch.client.opensearch.indices.CreateIndexResponse)3 IOException (java.io.IOException)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 ExecutionException (java.util.concurrent.ExecutionException)2 TimeUnit (java.util.concurrent.TimeUnit)2 OpenSearchClient (org.opensearch.client.opensearch.OpenSearchClient)2 OpenSearchException (org.opensearch.client.opensearch._types.OpenSearchException)2 Refresh (org.opensearch.client.opensearch._types.Refresh)2 HistogramAggregate (org.opensearch.client.opensearch._types.aggregations.HistogramAggregate)2 Property (org.opensearch.client.opensearch._types.mapping.Property)2 NodesResponse (org.opensearch.client.opensearch.cat.NodesResponse)2 BulkResponse (org.opensearch.client.opensearch.core.BulkResponse)2 ClearScrollResponse (org.opensearch.client.opensearch.core.ClearScrollResponse)2 GetResponse (org.opensearch.client.opensearch.core.GetResponse)2 IndexResponse (org.opensearch.client.opensearch.core.IndexResponse)2