Search in sources :

Example 6 with SearchResponse

use of co.elastic.clients.elasticsearch.core.SearchResponse in project elasticsearch-java by elastic.

the class RequestTest method testSearchAggregation.

@Test
public void testSearchAggregation() throws IOException {
    client.create(_1 -> _1.index("products").id("A").document(new Product(5)).refresh(Refresh.True));
    client.create(_1 -> _1.index("products").id("B").document(new Product(15)).refresh(Refresh.True));
    client.create(_1 -> _1.index("products").id("C").document(new Product(25)).refresh(Refresh.True));
    SearchResponse<Product> searchResponse = client.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 : CreateIndexResponse(co.elastic.clients.elasticsearch.indices.CreateIndexResponse) SearchResponse(co.elastic.clients.elasticsearch.core.SearchResponse) BeforeClass(org.junit.BeforeClass) RequestItem(co.elastic.clients.elasticsearch.core.msearch.RequestItem) CompletableFuture(java.util.concurrent.CompletableFuture) IndexState(co.elastic.clients.elasticsearch.indices.IndexState) BooleanResponse(co.elastic.clients.transport.endpoints.BooleanResponse) DateTime(co.elastic.clients.util.DateTime) Map(java.util.Map) OperationType(co.elastic.clients.elasticsearch.core.bulk.OperationType) ModelTestCase(co.elastic.clients.elasticsearch.model.ModelTestCase) Property(co.elastic.clients.elasticsearch._types.mapping.Property) Refresh(co.elastic.clients.elasticsearch._types.Refresh) ElasticsearchException(co.elastic.clients.elasticsearch._types.ElasticsearchException) HistogramAggregate(co.elastic.clients.elasticsearch._types.aggregations.HistogramAggregate) NodesResponse(co.elastic.clients.elasticsearch.cat.NodesResponse) GetResponse(co.elastic.clients.elasticsearch.core.GetResponse) ElasticsearchTestServer(co.elastic.clients.elasticsearch.ElasticsearchTestServer) Test(org.junit.Test) IOException(java.io.IOException) GetIndexResponse(co.elastic.clients.elasticsearch.indices.GetIndexResponse) Instant(java.time.Instant) GetIndicesSettingsResponse(co.elastic.clients.elasticsearch.indices.GetIndicesSettingsResponse) GetMappingResponse(co.elastic.clients.elasticsearch.indices.GetMappingResponse) MsearchResponse(co.elastic.clients.elasticsearch.core.MsearchResponse) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) ClosePointInTimeResponse(co.elastic.clients.elasticsearch.core.ClosePointInTimeResponse) DateTimeFormatter(java.time.format.DateTimeFormatter) BulkResponse(co.elastic.clients.elasticsearch.core.BulkResponse) ElasticsearchClient(co.elastic.clients.elasticsearch.ElasticsearchClient) DiskUsageResponse(co.elastic.clients.elasticsearch.indices.DiskUsageResponse) ClearScrollResponse(co.elastic.clients.elasticsearch.core.ClearScrollResponse) Assert(org.junit.Assert) Collections(java.util.Collections) IndexResponse(co.elastic.clients.elasticsearch.core.IndexResponse) ElasticsearchAsyncClient(co.elastic.clients.elasticsearch.ElasticsearchAsyncClient) HistogramAggregate(co.elastic.clients.elasticsearch._types.aggregations.HistogramAggregate) Test(org.junit.Test)

Example 7 with SearchResponse

use of co.elastic.clients.elasticsearch.core.SearchResponse in project elasticsearch-java by elastic.

the class ApiConventionsTest method builderIntervals.

@Test(expected = TransportException.class)
public void builderIntervals() throws Exception {
    ElasticsearchClient client = new ElasticsearchClient(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 : CreateIndexResponse(co.elastic.clients.elasticsearch.indices.CreateIndexResponse) SearchRequest(co.elastic.clients.elasticsearch.core.SearchRequest) Arrays(java.util.Arrays) SortOrder(co.elastic.clients.elasticsearch._types.SortOrder) SearchResponse(co.elastic.clients.elasticsearch.core.SearchResponse) LogManager(java.util.logging.LogManager) TransportException(co.elastic.clients.transport.TransportException) Test(org.junit.Test) HashMap(java.util.HashMap) NodeStatistics(co.elastic.clients.elasticsearch._types.NodeStatistics) Logger(java.util.logging.Logger) Aggregation(co.elastic.clients.elasticsearch._types.aggregations.Aggregation) Alias(co.elastic.clients.elasticsearch.indices.Alias) List(java.util.List) ElasticsearchTransport(co.elastic.clients.transport.ElasticsearchTransport) CreateIndexRequest(co.elastic.clients.elasticsearch.indices.CreateIndexRequest) ApiTypeHelper(co.elastic.clients.util.ApiTypeHelper) Map(java.util.Map) Query(co.elastic.clients.elasticsearch._types.query_dsl.Query) ElasticsearchClient(co.elastic.clients.elasticsearch.ElasticsearchClient) Assert(org.junit.Assert) ElasticsearchAsyncClient(co.elastic.clients.elasticsearch.ElasticsearchAsyncClient) ElasticsearchClient(co.elastic.clients.elasticsearch.ElasticsearchClient) Test(org.junit.Test)

Example 8 with SearchResponse

use of co.elastic.clients.elasticsearch.core.SearchResponse in project opentelemetry-plugin by jenkinsci.

the class OpenTelemetryLogToElasticsearchIT method test.

@Test
public void test() throws Exception {
    InputStream envAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(".env");
    Assert.assertNotNull(".env file not found in classpath", envAsStream);
    Properties env = new Properties();
    env.load(envAsStream);
    Map<String, String> configuration = new HashMap<>();
    env.forEach((k, v) -> configuration.put(k.toString(), v.toString()));
    configuration.put("otel.traces.exporter", "otlp");
    configuration.put("otel.metrics.exporter", "otlp");
    configuration.put("otel.logs.exporter", "otlp");
    final int LOG_MESSAGE_COUNT = 100;
    String traceId;
    // PRODUCE OPEN TELEMETRY LOG MESSAGES
    {
        AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder().addPropertiesSupplier(() -> configuration).build();
        try {
            OpenTelemetrySdk sdk = autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk();
            Tracer tracer = sdk.getTracer("test");
            LogEmitter logEmitter = sdk.getSdkLogEmitterProvider().get("test");
            Span span = tracer.spanBuilder("my-test-pipeline").startSpan();
            try (Scope scope = span.makeCurrent()) {
                for (int i = 0; i < LOG_MESSAGE_COUNT; i++) {
                    logEmitter.logBuilder().setContext(Context.current()).setBody("Log Message " + i).setAttributes(Attributes.of(AttributeKey.stringKey("myStringAttribute"), "Value " + i, AttributeKey.longKey("myNumericAttribute"), (long) i)).emit();
                    Thread.sleep(RANDOM.nextInt(100));
                }
            } finally {
                span.end();
            }
            traceId = span.getSpanContext().getTraceId();
        } finally {
            autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk().getSdkLogEmitterProvider().close();
            autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk().getSdkTracerProvider().close();
        }
    }
    Thread.sleep(3_000);
    // VERIFY LOG MESSAGES IN ELASTICSEARCH
    {
        String elasticsearchUrl = configuration.get("elasticsearch.url");
        String elasticsearchUsername = configuration.get("elasticsearch.username");
        String elasticsearchPassword = configuration.get("elasticsearch.password");
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(elasticsearchUsername, elasticsearchPassword));
        RestClient restClient = RestClient.builder(HttpHost.create(elasticsearchUrl)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)).build();
        RestClientTransport elasticsearchTransport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient elasticsearchClient = new ElasticsearchClient(elasticsearchTransport);
        SearchRequest searchRequest = new SearchRequest.Builder().index("logs-apm.app-*").size(500).sort(s -> s.field(f -> f.field("@timestamp").order(SortOrder.Asc))).query(q -> q.match(m -> m.field("trace.id").query(FieldValue.of(traceId)))).build();
        SearchResponse<ObjectNode> searchResponse = elasticsearchClient.search(searchRequest, ObjectNode.class);
        List<Hit<ObjectNode>> hits = searchResponse.hits().hits();
        if (hits.size() != LOG_MESSAGE_COUNT) {
            System.err.println("Invalid number of log messages: actual: " + hits.size() + ", expected: " + LOG_MESSAGE_COUNT);
        }
        for (Hit<ObjectNode> hit : hits) {
            ObjectNode source = hit.source();
            ObjectNode labels = (ObjectNode) source.findValue("labels");
            ObjectNode numericLabels = (ObjectNode) source.findValue("numeric_labels");
            try {
                String message = source.findValue("message").asText();
                String myStringAttribute = labels.findValue("myStringAttribute").asText();
                long myNumericAttribute = numericLabels.findValue("myNumericAttribute").longValue();
                System.out.println(hit.id() + "\tmessage:'" + message + "', \tmyStringAttribute: '" + myStringAttribute + "', myNumericAttribute: " + myNumericAttribute);
            } catch (Exception e) {
                System.err.println("Error parsing " + source);
            }
        }
    }
}
Also used : RestClientTransport(co.elastic.clients.transport.rest_client.RestClientTransport) RestClient(org.elasticsearch.client.RestClient) SearchRequest(co.elastic.clients.elasticsearch.core.SearchRequest) SearchResponse(co.elastic.clients.elasticsearch.core.SearchResponse) OpenTelemetrySdk(io.opentelemetry.sdk.OpenTelemetrySdk) Attributes(io.opentelemetry.api.common.Attributes) HashMap(java.util.HashMap) Random(java.util.Random) Tracer(io.opentelemetry.api.trace.Tracer) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AutoConfiguredOpenTelemetrySdk(io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk) Map(java.util.Map) FieldValue(co.elastic.clients.elasticsearch._types.FieldValue) Context(io.opentelemetry.context.Context) Properties(java.util.Properties) SortOrder(co.elastic.clients.elasticsearch._types.SortOrder) Span(io.opentelemetry.api.trace.Span) Scope(io.opentelemetry.context.Scope) Test(org.junit.Test) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Hit(co.elastic.clients.elasticsearch.core.search.Hit) List(java.util.List) AuthScope(org.apache.http.auth.AuthScope) AttributeKey(io.opentelemetry.api.common.AttributeKey) ElasticsearchClient(co.elastic.clients.elasticsearch.ElasticsearchClient) LogEmitter(io.opentelemetry.sdk.logs.LogEmitter) Assert(org.junit.Assert) HttpHost(org.apache.http.HttpHost) JacksonJsonpMapper(co.elastic.clients.json.jackson.JacksonJsonpMapper) InputStream(java.io.InputStream) SearchRequest(co.elastic.clients.elasticsearch.core.SearchRequest) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HashMap(java.util.HashMap) Properties(java.util.Properties) Span(io.opentelemetry.api.trace.Span) RestClientTransport(co.elastic.clients.transport.rest_client.RestClientTransport) List(java.util.List) ElasticsearchClient(co.elastic.clients.elasticsearch.ElasticsearchClient) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) InputStream(java.io.InputStream) Tracer(io.opentelemetry.api.trace.Tracer) RestClient(org.elasticsearch.client.RestClient) JacksonJsonpMapper(co.elastic.clients.json.jackson.JacksonJsonpMapper) AutoConfiguredOpenTelemetrySdk(io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) SearchResponse(co.elastic.clients.elasticsearch.core.SearchResponse) Hit(co.elastic.clients.elasticsearch.core.search.Hit) Scope(io.opentelemetry.context.Scope) AuthScope(org.apache.http.auth.AuthScope) LogEmitter(io.opentelemetry.sdk.logs.LogEmitter) OpenTelemetrySdk(io.opentelemetry.sdk.OpenTelemetrySdk) AutoConfiguredOpenTelemetrySdk(io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk) Test(org.junit.Test)

Example 9 with SearchResponse

use of co.elastic.clients.elasticsearch.core.SearchResponse in project para-search-elasticsearch by Erudika.

the class ES method searchQueryRaw.

/**
 * Executes an ElasticSearch query. This is the core method of the class.
 * @param appid name of the {@link com.erudika.para.core.App}
 * @param type type of object
 * @param query the search query builder
 * @param pager a {@link com.erudika.para.core.utils.Pager}
 * @return a list of search results
 */
protected static SearchResponse<Map> searchQueryRaw(String appid, String type, QueryVariant query, Pager... pager) {
    if (StringUtils.isBlank(appid)) {
        return null;
    }
    Pager page = ESUtils.getPager(pager);
    SortOrder order = page.isDesc() ? SortOrder.Desc : SortOrder.Asc;
    int max = page.getLimit();
    int pageNum = (int) page.getPage();
    int start = (pageNum < 1 || pageNum > Para.getConfig().maxPages()) ? 0 : (pageNum - 1) * max;
    if (query == null) {
        query = QueryBuilders.matchAll().build();
    }
    if (!StringUtils.isBlank(type)) {
        query = QueryBuilders.bool().must(query._toQuery(), QueryBuilders.term().field(Config._TYPE).value(v -> v.stringValue(type)).build()._toQuery()).build();
    }
    SearchResponse<Map> hits = null;
    String debugQuery = "";
    try {
        SearchRequest.Builder search = new SearchRequest.Builder();
        search.index(getIndexName(appid)).searchType(SearchType.DfsQueryThenFetch).query(query._toQuery()).size(max).trackTotalHits(ESUtils.getTrackTotalHits());
        if (pageNum <= 1 && !StringUtils.isBlank(page.getLastKey())) {
            search.searchAfter(page.getLastKey());
            search.from(0);
            search.sort(SortOptions.of(b -> b.field(f -> f.field("_docid").order(order))));
        } else {
            search.from(start);
            for (SortOptions sortField : ESUtils.getSortFieldsFromPager(page)) {
                search.sort(sortField);
            }
        }
        debugQuery = search.toString();
        logger.debug("Elasticsearch query: {}", debugQuery);
        hits = getRESTClient().search(search.build(), Map.class);
        page.setCount(Optional.ofNullable(hits.hits().total()).orElse(TotalHits.of(t -> t.relation(TotalHitsRelation.Eq).value(page.getCount()))).value());
        if (hits.hits().hits().size() > 0) {
            Object id = hits.hits().hits().get(hits.hits().hits().size() - 1).source().get("_docid");
            if (id != null) {
                page.setLastKey(id.toString());
            }
        }
    } catch (Exception e) {
        Throwable cause = e.getCause();
        String msg = cause != null ? cause.getMessage() : e.getMessage();
        logger.debug("No search results for type '{}' in app '{}': {}.\nQuery: {}", type, appid, msg, debugQuery);
    }
    return hits;
}
Also used : Arrays(java.util.Arrays) BulkOperation(co.elastic.clients.elasticsearch.core.bulk.BulkOperation) Like(co.elastic.clients.elasticsearch._types.query_dsl.Like) ESUtils.getNestedKey(com.erudika.para.server.search.es.ESUtils.getNestedKey) LoggerFactory(org.slf4j.LoggerFactory) TotalHitsRelation(co.elastic.clients.elasticsearch.core.search.TotalHitsRelation) ESUtils.getRESTClient(com.erudika.para.server.search.es.ESUtils.getRESTClient) StringUtils(org.apache.commons.lang3.StringUtils) ESUtils.qs(com.erudika.para.server.search.es.ESUtils.qs) ESUtils.convertQueryStringToNestedQuery(com.erudika.para.server.search.es.ESUtils.convertQueryStringToNestedQuery) PROPS_PREFIX(com.erudika.para.server.search.es.ESUtils.PROPS_PREFIX) Map(java.util.Map) FieldValue(co.elastic.clients.elasticsearch._types.FieldValue) ESUtils.getTermsQuery(com.erudika.para.server.search.es.ESUtils.getTermsQuery) Config(com.erudika.para.core.utils.Config) ParaObject(com.erudika.para.core.ParaObject) GetResponse(co.elastic.clients.elasticsearch.core.GetResponse) ESUtils.nestedMode(com.erudika.para.server.search.es.ESUtils.nestedMode) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Tag(com.erudika.para.core.Tag) ESUtils.executeRequests(com.erudika.para.server.search.es.ESUtils.executeRequests) Optional(java.util.Optional) Para(com.erudika.para.core.utils.Para) QueryBuilders(co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders) App(com.erudika.para.core.App) SearchRequest(co.elastic.clients.elasticsearch.core.SearchRequest) SearchResponse(co.elastic.clients.elasticsearch.core.SearchResponse) SearchType(co.elastic.clients.elasticsearch._types.SearchType) ESUtils.getPager(com.erudika.para.server.search.es.ESUtils.getPager) HashMap(java.util.HashMap) ChildScoreMode(co.elastic.clients.elasticsearch._types.query_dsl.ChildScoreMode) Pager(com.erudika.para.core.utils.Pager) ArrayList(java.util.ArrayList) ESUtils.keyValueBoolQuery(com.erudika.para.server.search.es.ESUtils.keyValueBoolQuery) TotalHits(co.elastic.clients.elasticsearch.core.search.TotalHits) DAO(com.erudika.para.core.persistence.DAO) LinkedList(java.util.LinkedList) BoolQuery(co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery) ESUtils.nestedPropsQuery(com.erudika.para.server.search.es.ESUtils.nestedPropsQuery) Logger(org.slf4j.Logger) SortOrder(co.elastic.clients.elasticsearch._types.SortOrder) Address(com.erudika.para.core.Address) ESUtils.getValueFieldName(com.erudika.para.server.search.es.ESUtils.getValueFieldName) ESUtils.getIndexName(com.erudika.para.server.search.es.ESUtils.getIndexName) Utils(com.erudika.para.core.utils.Utils) TimeUnit(java.util.concurrent.TimeUnit) Hit(co.elastic.clients.elasticsearch.core.search.Hit) Query(co.elastic.clients.elasticsearch._types.query_dsl.Query) QueryVariant(co.elastic.clients.elasticsearch._types.query_dsl.QueryVariant) SortOptions(co.elastic.clients.elasticsearch._types.SortOptions) Collections(java.util.Collections) SearchRequest(co.elastic.clients.elasticsearch.core.SearchRequest) SortOrder(co.elastic.clients.elasticsearch._types.SortOrder) ESUtils.getPager(com.erudika.para.server.search.es.ESUtils.getPager) Pager(com.erudika.para.core.utils.Pager) ParaObject(com.erudika.para.core.ParaObject) Map(java.util.Map) HashMap(java.util.HashMap) SortOptions(co.elastic.clients.elasticsearch._types.SortOptions)

Aggregations

SearchResponse (co.elastic.clients.elasticsearch.core.SearchResponse)9 ElasticsearchClient (co.elastic.clients.elasticsearch.ElasticsearchClient)6 Collections (java.util.Collections)6 SortOrder (co.elastic.clients.elasticsearch._types.SortOrder)5 SearchRequest (co.elastic.clients.elasticsearch.core.SearchRequest)5 Hit (co.elastic.clients.elasticsearch.core.search.Hit)5 List (java.util.List)5 Map (java.util.Map)5 Test (org.junit.Test)5 FieldValue (co.elastic.clients.elasticsearch._types.FieldValue)4 Query (co.elastic.clients.elasticsearch._types.query_dsl.Query)4 GetResponse (co.elastic.clients.elasticsearch.core.GetResponse)4 Assert (org.junit.Assert)4 ElasticsearchAsyncClient (co.elastic.clients.elasticsearch.ElasticsearchAsyncClient)3 CreateIndexResponse (co.elastic.clients.elasticsearch.indices.CreateIndexResponse)3 HashMap (java.util.HashMap)3 TimeUnit (java.util.concurrent.TimeUnit)3 ElasticsearchTestServer (co.elastic.clients.elasticsearch.ElasticsearchTestServer)2 ElasticsearchException (co.elastic.clients.elasticsearch._types.ElasticsearchException)2 Refresh (co.elastic.clients.elasticsearch._types.Refresh)2