Search in sources :

Example 1 with SearchTemplateRequest

use of org.elasticsearch.script.mustache.SearchTemplateRequest in project apm-agent-java by elastic.

the class AbstractEs6_4ClientInstrumentationTest method testSearchTemplateRequest_validateSpanContentAndDbContext.

@Test
public void testSearchTemplateRequest_validateSpanContentAndDbContext() throws InterruptedException, ExecutionException, IOException {
    createDocument();
    reporter.reset();
    SearchTemplateRequest searchTemplateRequest = prepareSearchTemplateRequest();
    SearchTemplateResponse response = doSearchTemplate(searchTemplateRequest);
    verifyTotalHits(response.getResponse().getHits());
    List<Span> spans = reporter.getSpans();
    assertThat(spans).hasSize(1);
    Span span = spans.get(0);
    validateSpanContent(span, String.format("Elasticsearch: GET /%s/_search/template", INDEX), 200, "GET");
    validateDbContextContent(span, "{\"source\":\"{  \\\"query\\\": { \\\"term\\\" : { \\\"{{field}}\\\" : \\\"{{value}}\\\" } },  \\\"size\\\" : \\\"{{size}}\\\"}\",\"params\":{\"field\":\"foo\",\"size\":5,\"value\":\"bar\"},\"explain\":false,\"profile\":false}");
    deleteDocument();
}
Also used : SearchTemplateRequest(org.elasticsearch.script.mustache.SearchTemplateRequest) MultiSearchTemplateRequest(org.elasticsearch.script.mustache.MultiSearchTemplateRequest) MultiSearchTemplateResponse(org.elasticsearch.script.mustache.MultiSearchTemplateResponse) SearchTemplateResponse(org.elasticsearch.script.mustache.SearchTemplateResponse) Span(co.elastic.apm.agent.impl.transaction.Span) AbstractEsClientInstrumentationTest(co.elastic.apm.agent.esrestclient.AbstractEsClientInstrumentationTest) Test(org.junit.Test)

Example 2 with SearchTemplateRequest

use of org.elasticsearch.script.mustache.SearchTemplateRequest in project spring-data-elasticsearch by spring-projects.

the class ReactiveElasticsearchClientIntegrationTests method inlineSearchTemplateShouldFindMatchingDocuments.

// #1725
@Test
public void inlineSearchTemplateShouldFindMatchingDocuments() {
    addSourceDocument().to(INDEX_I);
    addSourceDocument().to(INDEX_I);
    Map<String, Object> testDoc = new LinkedHashMap<>();
    testDoc.put("firstname", "inline");
    testDoc.put("lastname", "template");
    add(testDoc).to(INDEX_I);
    SearchTemplateRequest request = new SearchTemplateRequest(new SearchRequest(INDEX_I));
    request.setScriptType(ScriptType.INLINE);
    request.setScript("{\"query\":{\"match\":{\"firstname\":\"{{firstname}}\"}}}");
    Map<String, Object> params = new LinkedHashMap<>();
    params.put("firstname", "inline");
    request.setScriptParams(params);
    client.searchTemplate(request).as(StepVerifier::create).expectNextCount(1).verifyComplete();
}
Also used : SearchRequest(org.elasticsearch.action.search.SearchRequest) SearchTemplateRequest(org.elasticsearch.script.mustache.SearchTemplateRequest) StepVerifier(reactor.test.StepVerifier) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.jupiter.api.Test) SpringIntegrationTest(org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest)

Example 3 with SearchTemplateRequest

use of org.elasticsearch.script.mustache.SearchTemplateRequest in project apiman by apiman.

the class EsRegistry method listClientVersions.

@Override
@SuppressWarnings("nls")
public void listClientVersions(String organizationId, String clientId, int page, int pageSize, IAsyncResultHandler<List<String>> handler) {
    String query = "{" + "  \"query\": {" + "    \"bool\": {" + "      \"filter\": [" + "        {" + "          \"term\": {" + // organizationId
    "            \"organizationId\": \"{{organizationId}}\"" + "          }" + "        }," + "        {" + "          \"term\": {" + // clientId
    "            \"clientId\": \"{{clientId}}\"" + "          }" + "        }" + "      ]" + "    }" + "  }," + "    \"aggs\": {" + "      \"client_versions\": {" + "        \"terms\": {" + // only return version fields of clients
    "          \"field\": \"version\"" + "        }" + "      }" + "    }" + "}";
    SearchTemplateRequest searchTemplateRequest = new SearchTemplateRequest();
    searchTemplateRequest.setRequest(new SearchRequest(getIndexPrefix() + EsConstants.INDEX_CLIENTS));
    searchTemplateRequest.setScriptType(ScriptType.INLINE);
    searchTemplateRequest.setScript(query);
    Map<String, Object> scriptParams = new HashMap<>();
    scriptParams.put("organizationId", organizationId);
    scriptParams.put("clientId", clientId);
    searchTemplateRequest.setScriptParams(scriptParams);
    try {
        SearchTemplateResponse response = getClient().searchTemplate(searchTemplateRequest, RequestOptions.DEFAULT);
        SearchResponse searchResponse = response.getResponse();
        List terms = ((ParsedTerms) searchResponse.getAggregations().asMap().get("client_versions")).getBuckets();
        // Grab only the name of each aggregation (we don't care about count
        List<String> results = (List<String>) terms.stream().map(o -> ((ParsedTerms.ParsedBucket) o).getKey()).collect(Collectors.toList());
        handler.handle(AsyncResultImpl.create(results));
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
}
Also used : SearchRequest(org.elasticsearch.action.search.SearchRequest) ParsedTerms(org.elasticsearch.search.aggregations.bucket.terms.ParsedTerms) HashMap(java.util.HashMap) SearchTemplateRequest(org.elasticsearch.script.mustache.SearchTemplateRequest) SearchTemplateResponse(org.elasticsearch.script.mustache.SearchTemplateResponse) List(java.util.List) IOException(java.io.IOException) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 4 with SearchTemplateRequest

use of org.elasticsearch.script.mustache.SearchTemplateRequest in project apiman by apiman.

the class EsRegistry method lookupClient.

/**
 * Searches for a client by its orgid:clientId:version and returns it.
 * @param orgId the organization id
 * @param clientId the client id
 * @param version the version
 */
// Do beans need escaping or will that be done 'automatically'. Test it. Strings do, but probably only quotes?
@SuppressWarnings("nls")
private Client lookupClient(String orgId, String clientId, String version) {
    String query = "{" + "  \"query\": {" + "        \"bool\": {" + "            \"filter\": [{" + "                    \"term\": {" + // orgId
    "                        \"organizationId\": \"{{organizationId}}\" " + "                    }" + "          }," + "          {" + "                    \"term\": {" + // clientId
    "                        \"clientId\": \"{{clientId}}\" " + "                    }" + "          }," + "          {" + "                    \"term\": {" + // version
    "                        \"version\": \"{{version}}\" " + "          }" + "      }" + "            ]" + "    }" + "  }" + "}";
    SearchTemplateRequest searchTemplateRequest = new SearchTemplateRequest();
    searchTemplateRequest.setRequest(new SearchRequest(getIndexPrefix() + EsConstants.INDEX_CLIENTS));
    searchTemplateRequest.setScriptType(ScriptType.INLINE);
    searchTemplateRequest.setScript(query);
    Map<String, Object> scriptParams = new HashMap<>();
    scriptParams.put("organizationId", orgId);
    scriptParams.put("clientId", clientId);
    scriptParams.put("version", version);
    searchTemplateRequest.setScriptParams(scriptParams);
    Client client;
    try {
        SearchTemplateResponse response = getClient().searchTemplate(searchTemplateRequest, RequestOptions.DEFAULT);
        SearchResponse searchResponse = response.getResponse();
        SearchHits hits = searchResponse.getHits();
        if (hits.getTotalHits().value == 0) {
            throw new IOException();
        }
        String sourceAsString = response.getResponse().getHits().getAt(0).getSourceAsString();
        client = JSON_MAPPER.readValue(sourceAsString, Client.class);
    } catch (IOException e) {
        // $NON-NLS-1$
        throw new ClientNotFoundException(Messages.i18n.format("EsRegistry.ClientNotFound"), e);
    }
    return client;
}
Also used : SearchRequest(org.elasticsearch.action.search.SearchRequest) ClientNotFoundException(io.apiman.gateway.engine.beans.exceptions.ClientNotFoundException) HashMap(java.util.HashMap) SearchTemplateRequest(org.elasticsearch.script.mustache.SearchTemplateRequest) SearchTemplateResponse(org.elasticsearch.script.mustache.SearchTemplateResponse) SearchHits(org.elasticsearch.search.SearchHits) IOException(java.io.IOException) Client(io.apiman.gateway.engine.beans.Client) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 5 with SearchTemplateRequest

use of org.elasticsearch.script.mustache.SearchTemplateRequest in project skywalking-java by apache.

the class RestHighLevelClientCase method searchTemplateAsync.

private void searchTemplateAsync(RestHighLevelClient client, String indexName) throws IOException {
    SearchTemplateRequest searchTemplateRequest = new SearchTemplateRequest();
    searchTemplateRequest.setRequest(new SearchRequest(indexName));
    searchTemplateRequest.setScriptType(ScriptType.INLINE);
    searchTemplateRequest.setScript("{\n" + "  \"from\": \"{{from}}\",\n" + "  \"size\": \"{{size}}\",\n" + "  \"query\": {\n" + "    \"term\": {\n" + "      \"{{field}}\": {\n" + "        \"value\": \"{{value}}\"\n" + "      }\n" + "    }\n" + "  }\n" + "}");
    Map<String, Object> scriptParams = new HashMap<>();
    scriptParams.put("field", "author");
    scriptParams.put("value", "Marker");
    scriptParams.put("size", 10);
    scriptParams.put("from", 0);
    searchTemplateRequest.setScriptParams(scriptParams);
    client.searchTemplateAsync(searchTemplateRequest, RequestOptions.DEFAULT, new ActionListener<SearchTemplateResponse>() {

        @Override
        public void onResponse(final SearchTemplateResponse searchTemplateResponse) {
            if (!(searchTemplateResponse.getResponse().getHits().totalHits > 0)) {
                String message = "elasticsearch searchTemplateAsync data fail.";
                LOGGER.error(message);
                throw new RuntimeException(message);
            }
        }

        @Override
        public void onFailure(final Exception e) {
            LOGGER.error(e);
            throw new RuntimeException();
        }
    });
}
Also used : SearchRequest(org.elasticsearch.action.search.SearchRequest) HashMap(java.util.HashMap) SearchTemplateRequest(org.elasticsearch.script.mustache.SearchTemplateRequest) SearchTemplateResponse(org.elasticsearch.script.mustache.SearchTemplateResponse) IOException(java.io.IOException)

Aggregations

SearchTemplateRequest (org.elasticsearch.script.mustache.SearchTemplateRequest)14 SearchRequest (org.elasticsearch.action.search.SearchRequest)10 HashMap (java.util.HashMap)7 SearchTemplateResponse (org.elasticsearch.script.mustache.SearchTemplateResponse)6 IOException (java.io.IOException)4 List (java.util.List)3 MultiSearchTemplateRequest (org.elasticsearch.script.mustache.MultiSearchTemplateRequest)3 AbstractEsClientInstrumentationTest (co.elastic.apm.agent.esrestclient.AbstractEsClientInstrumentationTest)2 Span (co.elastic.apm.agent.impl.transaction.Span)2 LinkedHashMap (java.util.LinkedHashMap)2 PutMappingRequest (org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest)2 BulkRequest (org.elasticsearch.action.bulk.BulkRequest)2 DeleteRequest (org.elasticsearch.action.delete.DeleteRequest)2 GetRequest (org.elasticsearch.action.get.GetRequest)2 MultiGetRequest (org.elasticsearch.action.get.MultiGetRequest)2 IndexRequest (org.elasticsearch.action.index.IndexRequest)2 MultiSearchRequest (org.elasticsearch.action.search.MultiSearchRequest)2 SearchResponse (org.elasticsearch.action.search.SearchResponse)2 UpdateRequest (org.elasticsearch.action.update.UpdateRequest)2 DeleteByQueryRequest (org.elasticsearch.index.reindex.DeleteByQueryRequest)2