io.searchbox.core.SearchResult Java Examples

The following examples show how to use io.searchbox.core.SearchResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IndexFunctionsDaoTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsValidFunction()
{
    SearchResult jestResult = mock(SearchResult.class);
    // Build mocks
    when(jestClientHelper.execute(any())).thenReturn(jestResult);
    when(jestResult.getSourceAsString()).thenReturn("JSON");

    // Call the method under test
    boolean isValid = indexFunctionsDao.isValidDocumentIndex("INDEX_NAME", "DOCUMENT_TYPE", "ID", "JSON");
    assertThat("IsValid is false when it should have been true.", isValid, is(true));

    verify(jestClientHelper, times(1)).execute(any());
    verify(jestResult).getSourceAsString();
    verifyNoMoreInteractions(jestClientHelper);
}
 
Example #2
Source File: EsStorage.java    From apiman with Apache License 2.0 6 votes vote down vote up
private void initScroll() throws StorageException {
    try {
        Search search = new Search.Builder(query)
                .addIndex(getIndexName())
                .addType(entityType)
                .setParameter(Parameters.SCROLL, "1m")
                .addSort(sort)
                .build();
        SearchResult response = esClient.execute(search);
        if (!response.isSucceeded()) {
            throw new StorageException("Scrolled query failed " + response.getErrorMessage());
        }
        scrollId = response.getJsonObject().get("_scroll_id").getAsString();
        this.hits = (List) response.getHits(Map.class);
    } catch (IOException e) {
        throw new StorageException(e);
    }
}
 
Example #3
Source File: IndexFunctionsDaoTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateIndexDocumentsFunctionWithFailures()
{
    SearchResult jestResult = mock(SearchResult.class);
    JestResult jestResultAliases = mock(JestResult.class);
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("INDEX_NAME_1", "INDEX_NAME");
    jsonObject.addProperty("INDEX_NAME_2", "INDEX_NAME");
    // Build mocks
    when(jestClientHelper.execute(any())).thenReturn(jestResult);
    when(jestResult.isSucceeded()).thenReturn(false);
    when(jestClientHelper.execute(any())).thenReturn(jestResultAliases);
    when(jestResultAliases.isSucceeded()).thenReturn(true);
    when(jestResultAliases.getJsonObject()).thenReturn(jsonObject);

    // Call the method under test
    Map<String, String> documentMap = new HashMap<>();
    documentMap.put("1", "JSON");
    indexFunctionsDao.updateIndexDocuments("INDEX_NAME", "DOCUMENT_TYPE", documentMap);

    // Verify the calls to external methods
    verify(jestClientHelper, times(3)).execute(any());
    verifyNoMoreInteractions(jestClientHelper);
}
 
Example #4
Source File: ElasticsearchService.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Get the top {@literal size} most active tags.
 *
 * @param size the number of top tags to retrieve
 * @return a list of tag ids
 */
public List<Long> getTopTags(Integer size) {
  String query = String.format("{\n" +
      "  \"sort\" : [ {\n" +
      "    \"timestamp\" : {\n" +
      "      \"order\" : \"desc\"\n" +
      "    }\n" +
      "  } ],\n" +
      "  \"aggregations\" : {\n" +
      "    \"group-by-id\" : {\n" +
      "      \"terms\" : {\n" +
      "        \"field\" : \"id\",\n" +
      "        \"size\" : %d\n" +
      "      }\n" +
      "    }\n" +
      "  }\n" +
      "}", size);
  Function<SearchResult, List<Long>> converter = result ->
      new ArrayList<>(result.getAggregations().getTermsAggregation("group-by-id").getBuckets()
          .stream()
          .map(bucket -> Long.valueOf(bucket.getKey()))
          .collect(Collectors.toList()));
  return findTagsByQuery(query, converter, timeSeriesIndex, "Error querying top most active tags");
}
 
Example #5
Source File: EsStorage.java    From apiman with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private void fetch() throws StorageException {
    try {
        Builder builder = new SearchScroll.Builder(scrollId, "1m");
        SearchScroll scroll = new SearchScroll(builder) {
            @Override
            public JestResult createNewElasticSearchResult(String responseBody, int statusCode,
                    String reasonPhrase, Gson gson) {
                return createNewElasticSearchResult(new SearchResult(gson), responseBody, statusCode, reasonPhrase, gson);
            }
        };
        SearchResult response = (SearchResult) esClient.execute(scroll);
        if (!response.isSucceeded()) {
            throw new StorageException("Scrolled fetch failed " + response.getErrorMessage());
        }
        this.hits = (List) response.getHits(Map.class);
    } catch (IOException e) {
        throw new StorageException(e);
    }
}
 
Example #6
Source File: ElasticSearchReportService.java    From vind with Apache License 2.0 6 votes vote down vote up
@Override
public LinkedHashMap<String, JsonObject> getTopFilterFields() {
    final String query = elasticClient.loadQueryFromFile("topFilterFields",
            getEsFilters(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getApplicationId(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.getFrom().toInstant().toEpochMilli(),
            this.getTo().toInstant().toEpochMilli(),
            this.configuration.getMessageWrapper());

    final SearchResult searchResult = elasticClient.getQuery(query);
    final List<TermsAggregation.Entry> termEntries = searchResult.getAggregations()
            .getTermsAggregation("filterFields")
            .getBuckets();
    final List<String> filterFields = termEntries.stream()
            .map(TermsAggregation.Entry::getKey)
            .collect(Collectors.toList());

    return prepareScopeFilterResults(filterFields, "Filter");
}
 
Example #7
Source File: ElasticSearchReportService.java    From vind with Apache License 2.0 6 votes vote down vote up
@Override
public LinkedHashMap<String, Long> getTopFilteredQueries() {
    final String query = elasticClient.loadQueryFromFile("topFilteredQueries",
            getEsFilters(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getApplicationId(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getReportWriterConfiguration().getQueryFilter(),
            this.configuration.getMessageWrapper(),
            this.getFrom().toInstant().toEpochMilli(),
            this.getTo().toInstant().toEpochMilli(),
            this.configuration.getMessageWrapper());


    final SearchResult searchResult = elasticClient.getQuery(query);
    final List<TermsAggregation.Entry> termEntries = searchResult.getAggregations().getTermsAggregation("queries").getBuckets();
    final LinkedHashMap<String, Long> result = new LinkedHashMap<>();
    termEntries.stream().sorted(Comparator.comparingLong(TermsAggregation.Entry::getCount).reversed())
            .forEach(entry -> result.put(entry.getKey(), entry.getCount()));

    return result;
}
 
Example #8
Source File: ElasticSearchReportService.java    From vind with Apache License 2.0 6 votes vote down vote up
@Override
public LinkedHashMap<String, Long> getTopQueries() {
    final String query = elasticClient.loadQueryFromFile("topQueries",
            getEsFilters(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getApplicationId(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.getFrom().toInstant().toEpochMilli(),
            this.getTo().toInstant().toEpochMilli(),
            this.configuration.getMessageWrapper());

    final SearchResult searchResult = elasticClient.getQuery(query);
    final List<TermsAggregation.Entry> termEntries = searchResult.getAggregations().getTermsAggregation("queries").getBuckets();
    final LinkedHashMap<String, Long> result = new LinkedHashMap<>();
    termEntries.stream().sorted(Comparator.comparingLong(TermsAggregation.Entry::getCount).reversed())
            .forEach(entry -> result.put(entry.getKey(), entry.getCount()));

    return result;
}
 
Example #9
Source File: ElasticSearchReportService.java    From vind with Apache License 2.0 6 votes vote down vote up
@Override
public LinkedHashMap<String, JsonObject> getTopSuggestionFields() {
    final String query = elasticClient.loadQueryFromFile("topSuggestionFields",
            getEsFilters(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getApplicationId(),
            this.configuration.getMessageWrapper(),
            this.getFrom().toInstant().toEpochMilli(),
            this.getTo().toInstant().toEpochMilli(),
            this.configuration.getMessageWrapper());

    final SearchResult searchResult = elasticClient.getQuery(query);
    final List<TermsAggregation.Entry> termEntries = searchResult.getAggregations()
            .getTermsAggregation("suggestionFields")
            .getBuckets();
    final List<String> suggestionFields = termEntries.stream()
            .map(TermsAggregation.Entry::getKey)
            .collect(Collectors.toList());

    return prepareScopeFilterResults(suggestionFields, "Suggest");
}
 
Example #10
Source File: ElasticSearchReportService.java    From vind with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getTopFacetFields() {
    final String query = elasticClient.loadQueryFromFile("topFacetFields",
            getEsFilters(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getApplicationId(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.getFrom().toInstant().toEpochMilli(),
            this.getTo().toInstant().toEpochMilli(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper());

    final SearchResult searchResult = elasticClient.getQuery(query);
    final List<TermsAggregation.Entry> termEntries = searchResult.getAggregations().getTermsAggregation("facets").getBuckets();
    return termEntries.stream()
            .map(TermsAggregation.Entry::getKey)
            .collect(Collectors.toList());
}
 
Example #11
Source File: ElasticSearchReportService.java    From vind with Apache License 2.0 6 votes vote down vote up
@Override
public LinkedHashMap<String, Long> getTopUsers() {
    final String query = elasticClient.loadQueryFromFile("topUsers",
            getEsFilters(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getApplicationId(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.getFrom().toInstant().toEpochMilli(),
            this.getTo().toInstant().toEpochMilli(),
            this.configuration.getMessageWrapper());

    final SearchResult searchResult = elasticClient.getQuery(query);
    final List<TermsAggregation.Entry> termEntries = searchResult.getAggregations().getTermsAggregation("user").getBuckets();
    final LinkedHashMap<String, Long> result = new LinkedHashMap<>();
    termEntries.stream().sorted(Comparator.comparingLong(TermsAggregation.Entry::getCount).reversed())
            .forEach(entry -> result.put(entry.getKey(), entry.getCount()));

    return result;
}
 
Example #12
Source File: ElasticSearchReportService.java    From vind with Apache License 2.0 6 votes vote down vote up
@Override
public LinkedHashMap<ZonedDateTime, Long> getTopDays() {
    final String query = elasticClient.loadQueryFromFile("topDays",
            getEsFilters(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getApplicationId(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.getFrom().toInstant().toEpochMilli(),
            this.getTo().toInstant().toEpochMilli(),
            this.configuration.getMessageWrapper());

    final SearchResult searchResult = elasticClient.getQuery(query);
    final LinkedHashMap<ZonedDateTime, Long> result = new LinkedHashMap<>();
    searchResult.getAggregations().getDateHistogramAggregation("days" )
            .getBuckets().stream().sorted(Comparator.comparingLong(DateHistogramAggregation.DateHistogram::getCount).reversed())
            .forEach( dateHistogram ->
                    result.put(ZonedDateTime.ofInstant(Instant.ofEpochMilli(dateHistogram.getTime()), this.getZoneId()), dateHistogram.getCount()));
    return result;
}
 
Example #13
Source File: IndexFunctionsDaoTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateIndexDocumentsFunction()
{
    SearchResult jestResult = mock(SearchResult.class);
    JestResult jestResultAliases = mock(JestResult.class);
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("INDEX_NAME_1", "INDEX_NAME");
    jsonObject.addProperty("INDEX_NAME_2", "INDEX_NAME");
    // Build mocks
    when(jestClientHelper.execute(any())).thenReturn(jestResult);
    when(jestResult.isSucceeded()).thenReturn(true);
    when(jestClientHelper.execute(any())).thenReturn(jestResultAliases);
    when(jestResultAliases.isSucceeded()).thenReturn(true);
    when(jestResultAliases.getJsonObject()).thenReturn(jsonObject);

    // Call the method under test
    Map<String, String> documentMap = new HashMap<>();
    documentMap.put("1", "JSON");
    indexFunctionsDao.updateIndexDocuments("INDEX_NAME", "DOCUMENT_TYPE", documentMap);

    // Verify the calls to external methods
    verify(jestClientHelper, times(3)).execute(any());
    verifyNoMoreInteractions(jestClientHelper);
}
 
Example #14
Source File: IndexFunctionsDaoTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testIdsInIndexFunction()
{
    JestResult jestResult = mock(JestResult.class);
    SearchResult searchResult = mock(SearchResult.class);
    List<String> idList = Arrays.asList("{id:1}");
    List<String> emptyList = new ArrayList<>();
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("_scroll_id", "100");
    when(jestClientHelper.execute(any(Search.class))).thenReturn(searchResult);
    when(searchResult.getSourceAsStringList()).thenReturn(idList);
    when(searchResult.getJsonObject()).thenReturn(jsonObject);
    when(jestClientHelper.execute(any(SearchScroll.class))).thenReturn(jestResult);
    when(jestResult.getSourceAsStringList()).thenReturn(emptyList);
    indexFunctionsDao.getIdsInIndex("INDEX_NAME", "DOCUMENT_TYPE");
    verify(jestClientHelper).execute(any(Search.class));
    verify(searchResult, times(2)).getSourceAsStringList();
    verify(searchResult).getJsonObject();
    verify(jestClientHelper).execute(any(SearchScroll.class));
    verify(jestResult).getSourceAsStringList();
}
 
Example #15
Source File: ElasticsearchService.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
public List<Long> getTopAlarms(Integer size) {
  String query = String.format("{\n" +
      "  \"aggregations\" : {\n" +
      "    \"group-by-id\" : {\n" +
      "      \"terms\" : {\n" +
      "        \"field\" : \"id\",\n" +
      "        \"size\" : %d\n" +
      "      }\n" +
      "    }\n" +
      "  }\n" +
      "}", size);
  Function<SearchResult, List<Long>> converter = result ->
      new ArrayList<>(result.getAggregations().getTermsAggregation("group-by-id").getBuckets()
          .stream()
          .map(bucket -> Long.valueOf(bucket.getKey()))
          .collect(Collectors.toList()));
  return findTagsByQuery(query, converter, alarmIndex,"Error querying top most active alarms");
}
 
Example #16
Source File: IndexFunctionsDaoTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteIndexDocumentsFunctionWithFailures()
{
    SearchResult jestResult = mock(SearchResult.class);
    JestResult jestResultAliases = mock(JestResult.class);
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("INDEX_NAME_1", "INDEX_NAME");
    jsonObject.addProperty("INDEX_NAME_2", "INDEX_NAME");
    // Build mocks
    when(jestClientHelper.execute(any())).thenReturn(jestResult);
    when(jestResult.isSucceeded()).thenReturn(false);
    when(jestClientHelper.execute(any())).thenReturn(jestResultAliases);
    when(jestResultAliases.isSucceeded()).thenReturn(true);
    when(jestResultAliases.getJsonObject()).thenReturn(jsonObject);
    // Call the method under test
    List<Long> businessObjectDefinitionIds = new ArrayList<>();
    businessObjectDefinitionIds.add(1L);
    indexFunctionsDao.deleteIndexDocuments("INDEX_NAME", "DOCUMENT_TYPE", businessObjectDefinitionIds);

    // Verify the calls to external methods
    verify(jestClientHelper, times(3)).execute(any());
    verifyNoMoreInteractions(jestClientHelper);
}
 
Example #17
Source File: ElasticsearchHelper.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Creates result type facet response dto
 *
 * @param searchResult search result
 *
 * @return result type facet response dto list
 */
public List<ResultTypeIndexSearchResponseDto> getResultTypeIndexSearchResponseDto(SearchResult searchResult)
{
    MetricAggregation metricAggregation = searchResult.getAggregations();
    TermsAggregation resultTypeAggregation = metricAggregation.getTermsAggregation(RESULT_TYPE_AGGS);

    List<TermsAggregation.Entry> buckets = resultTypeAggregation.getBuckets();

    List<ResultTypeIndexSearchResponseDto> resultTypeIndexSearchResponseDtos = new ArrayList<>();

    for (TermsAggregation.Entry entry : buckets)
    {
        ResultTypeIndexSearchResponseDto dto = new ResultTypeIndexSearchResponseDto();
        dto.setResultTypeCode(entry.getKeyAsString());
        dto.setResultTypeDisplayName(entry.getKeyAsString());
        dto.setCount(entry.getCount());
        resultTypeIndexSearchResponseDtos.add(dto);
    }

    return resultTypeIndexSearchResponseDtos;
}
 
Example #18
Source File: IndexFunctionsDaoTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteIndexDocumentsFunction()
{
    SearchResult jestResult = mock(SearchResult.class);
    JestResult jestResultAliases = mock(JestResult.class);
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("INDEX_NAME_1", "INDEX_NAME");
    jsonObject.addProperty("INDEX_NAME_2", "INDEX_NAME");
    // Build mocks
    when(jestClientHelper.execute(any())).thenReturn(jestResult);
    when(jestResult.isSucceeded()).thenReturn(true);
    when(jestClientHelper.execute(any())).thenReturn(jestResultAliases);
    when(jestResultAliases.isSucceeded()).thenReturn(true);
    when(jestResultAliases.getJsonObject()).thenReturn(jsonObject);
    // Call the method under test
    List<Long> businessObjectDefinitionIds = new ArrayList<>();
    businessObjectDefinitionIds.add(1L);
    indexFunctionsDao.deleteIndexDocuments("INDEX_NAME", "DOCUMENT_TYPE", businessObjectDefinitionIds);

    // Verify the calls to external methods
    verify(jestClientHelper, times(3)).execute(any());
    verifyNoMoreInteractions(jestClientHelper);
}
 
Example #19
Source File: IndexFunctionsDaoTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateIndexDocumentsFunctionWithFailures()
{
    SearchResult jestResult = mock(SearchResult.class);
    JestResult jestResultAliases = mock(JestResult.class);
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("INDEX_NAME_1", "INDEX_NAME");
    jsonObject.addProperty("INDEX_NAME_2", "INDEX_NAME");

    // Build mocks
    when(jestClientHelper.execute(any())).thenReturn(jestResult);
    when(jestClientHelper.execute(any())).thenReturn(jestResultAliases);
    when(jestResultAliases.isSucceeded()).thenReturn(true);
    when(jestResultAliases.getJsonObject()).thenReturn(jsonObject);
    when(jestResult.isSucceeded()).thenReturn(false);
    Map<String, String> documentMap = new HashMap<>();
    documentMap.put("1", "JSON");
    indexFunctionsDao.createIndexDocuments("INDEX_NAME", "DOCUMENT_TYPE", documentMap);

    verify(jestClientHelper, times(3)).execute(any());
    verify(jestResultAliases).getJsonObject();
    verifyNoMoreInteractions(jestClientHelper);
}
 
Example #20
Source File: IndexFunctionsDaoTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateIndexDocumentsFunction()
{
    SearchResult jestResult = mock(SearchResult.class);
    JestResult jestResultAliases = mock(JestResult.class);
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("INDEX_NAME_1", "INDEX_NAME");
    jsonObject.addProperty("INDEX_NAME_2", "INDEX_NAME");

    // Build mocks
    when(jestClientHelper.execute(any())).thenReturn(jestResult);
    when(jestResult.isSucceeded()).thenReturn(true);
    when(jestClientHelper.execute(any())).thenReturn(jestResultAliases);
    when(jestResultAliases.isSucceeded()).thenReturn(true);
    when(jestResultAliases.getJsonObject()).thenReturn(jsonObject);

    Map<String, String> documentMap = new HashMap<>();
    documentMap.put("1", "JSON");
    indexFunctionsDao.createIndexDocuments("INDEX_NAME", "DOCUMENT_TYPE", documentMap);

    verify(jestClientHelper, times(3)).execute(any());
    verify(jestResultAliases).getJsonObject();
    verifyNoMoreInteractions(jestClientHelper);
}
 
Example #21
Source File: IndexSearchDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts facet information from a {@link SearchResult} object
 *
 * @param request The specified {@link IndexSearchRequest}
 * @param searchResult A given {@link SearchResult} to extract the facet information from
 * @param bdefActiveIndex the name of the active index for business object definitions
 * @param tagActiveIndex the name os the active index for tags
 *
 * @return A list of {@link Facet} objects
 */
private List<Facet> extractFacets(IndexSearchRequest request, SearchResult searchResult, final String bdefActiveIndex, final String tagActiveIndex)
{
    ElasticsearchResponseDto elasticsearchResponseDto = new ElasticsearchResponseDto();
    if (request.getFacetFields().contains(ElasticsearchHelper.TAG_FACET))
    {
        elasticsearchResponseDto.setNestTagTypeIndexSearchResponseDtos(elasticsearchHelper.getNestedTagTagIndexSearchResponseDto(searchResult));
        elasticsearchResponseDto.setTagTypeIndexSearchResponseDtos(elasticsearchHelper.getTagTagIndexSearchResponseDto(searchResult));
    }
    if (request.getFacetFields().contains(ElasticsearchHelper.RESULT_TYPE_FACET))
    {
        elasticsearchResponseDto.setResultTypeIndexSearchResponseDtos(elasticsearchHelper.getResultTypeIndexSearchResponseDto(searchResult));
    }

    return elasticsearchHelper.getFacetsResponse(elasticsearchResponseDto, bdefActiveIndex, tagActiveIndex);
}
 
Example #22
Source File: JestClientHelperTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testSearchExecute() throws Exception
{
    // Mock
    Search search = mock(Search.class);
    SearchResult searchResult = mock(SearchResult.class);
    JestClient jestClient = mock(JestClient.class);
    when(jestClientFactory.getJestClient()).thenReturn(jestClient);
    when(jestClient.execute(search)).thenReturn(searchResult);

    // Test
    SearchResult result = jestClientHelper.execute(search);

    // Validate
    assertThat(result, is(not(nullValue())));

    // Verify
    verify(jestClientFactory).getJestClient();
    verify(jestClient).execute(search);
    verifyNoMoreInteractions(createdMocks.toArray());
}
 
Example #23
Source File: IndexFunctionsDaoTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsValidFunctionNotEqual()
{
    SearchResult jestResult = mock(SearchResult.class);
    // Build mocks
    when(jestClientHelper.execute(any())).thenReturn(jestResult);
    when(jestResult.getSourceAsString()).thenReturn("JSON_NOT_EQUAL");

    // Call the method under test
    boolean isValid = indexFunctionsDao.isValidDocumentIndex("INDEX_NAME", "DOCUMENT_TYPE", "ID", "JSON");
    assertThat("IsValid is true when it should have been false.", isValid, is(false));

    verify(jestClientHelper, times(1)).execute(any());
    verify(jestResult).getSourceAsString();
    verifyNoMoreInteractions(jestClientHelper);
}
 
Example #24
Source File: IndexFunctionsDaoTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsValidFunctionNull()
{
    SearchResult jestResult = mock(SearchResult.class);
    // Build mocks
    when(jestClientHelper.execute(any())).thenReturn(jestResult);
    when(jestResult.getSourceAsString()).thenReturn(null);

    // Call the method under test
    boolean isValid = indexFunctionsDao.isValidDocumentIndex("INDEX_NAME", "DOCUMENT_TYPE", "ID", "JSON");
    assertThat("IsValid is true when it should have been false.", isValid, is(false));

    verify(jestClientHelper, times(1)).execute(any());
    verify(jestResult).getSourceAsString();
    verifyNoMoreInteractions(jestClientHelper);
}
 
Example #25
Source File: ElasticSearchHelperTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetResultTypeIndexSearchResponseDtoSearchResult()
{
    SearchResult searchResult = mock(SearchResult.class);
    MetricAggregation metricAggregation = mock(MetricAggregation.class);
    TermsAggregation termsAggregation = mock(TermsAggregation.class);
    List<TermsAggregation.Entry> buckets = new ArrayList<>();
    buckets.add(new TermsAggregation("TermAggregation", new JsonObject()).new Entry(new JsonObject(), "key", 1L));

    when(searchResult.getAggregations()).thenReturn(metricAggregation);
    when(metricAggregation.getTermsAggregation(RESULT_TYPE_AGGS)).thenReturn(termsAggregation);
    when(termsAggregation.getBuckets()).thenReturn(buckets);

    List<ResultTypeIndexSearchResponseDto> result = elasticsearchHelper.getResultTypeIndexSearchResponseDto(searchResult);
    assertThat("Result is null.", result, is(notNullValue()));
}
 
Example #26
Source File: IndexFunctionsDaoTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsValidFunctionEmpty()
{
    SearchResult jestResult = mock(SearchResult.class);
    // Build mocks
    when(jestClientHelper.execute(any())).thenReturn(jestResult);
    when(jestResult.getSourceAsString()).thenReturn("");

    // Call the method under test
    boolean isValid = indexFunctionsDao.isValidDocumentIndex("INDEX_NAME", "DOCUMENT_TYPE", "ID", "JSON");
    assertThat("IsValid is true when it should have been false.", isValid, is(false));

    verify(jestClientHelper, times(1)).execute(any());
    verify(jestResult).getSourceAsString();
    verifyNoMoreInteractions(jestClientHelper);

}
 
Example #27
Source File: ElasticSearchReportService.java    From vind with Apache License 2.0 6 votes vote down vote up
@Override
public long getTotalRequests() {

    final String query = elasticClient.loadQueryFromFile("totalRequests",
            getEsFilters(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getApplicationId(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.configuration.getMessageWrapper(),
            this.getFrom().toInstant().toEpochMilli(),
            this.getTo().toInstant().toEpochMilli());

    final SearchResult result = elasticClient.getQuery(query);
    return result.getTotal();
}
 
Example #28
Source File: IndexFunctionsDaoTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateFunctionNoActionRequiredValidDocument()
{
    SearchResult jestResult = mock(SearchResult.class);
    // Build mocks
    when(jestClientHelper.execute(any())).thenReturn(jestResult);
    when(jestResult.getSourceAsString()).thenReturn("JSON");
    indexFunctionsDao.validateDocumentIndex("INDEX_NAME", "DOCUMENT_TYPE", "ID", "JSON");
    // Verify the calls to external methods
    verify(jestClientHelper, times(1)).execute(any());
    verify(jestResult).getSourceAsString();
    verifyNoMoreInteractions(jestClientHelper);
}
 
Example #29
Source File: ESRegistry.java    From apiman with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("nls")
public void listOrgs(IAsyncResultHandler<List<String>> handler) {
    try {
        String query =
                "{\n" +
                "    \"aggs\" : {\n" +
                "        \"all_orgs\" : {\n" +
                "            \"terms\" : { \"field\" : \"organizationId\" }\n" + // i.e. only records containing an orgId field.
                "        }\n" +
                "    }\n" +
                "}";
        Search search = new Search.Builder(query)
                .addIndex(getIndexName())
                .setParameter(Parameters.SIZE, 0)
                .build();
        SearchResult response = getClient().execute(search);
        // Aggregations section
        MetricAggregation aggregation = response.getAggregations();
        // Look at the terms subsection
        TermsAggregation terms = aggregation.getTermsAggregation("all_orgs");
        // Grab only the name of each aggregation (we don't care about count
        List<String> results = terms.getBuckets().stream()
                .map(TermsAggregation.Entry::getKey)
                .collect(Collectors.toList());
        handler.handle(AsyncResultImpl.create(results));
    } catch (IOException e) {
        handler.handle(AsyncResultImpl.create(e));
    }
}
 
Example #30
Source File: IndexFunctionsDaoTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateFunctionUpdate()
{
    SearchResult jestResult = mock(SearchResult.class);
    // Build mocks
    when(jestClientHelper.execute(any())).thenReturn(jestResult);
    when(jestResult.getSourceAsString()).thenReturn("JSON_UPDATE");
    indexFunctionsDao.validateDocumentIndex("INDEX_NAME", "DOCUMENT_TYPE", "ID", "JSON");
    // Verify the calls to external methods
    verify(jestClientHelper, times(2)).execute(any());
    verify(jestResult).getSourceAsString();
    verify(jestResult).isSucceeded();
    verifyNoMoreInteractions(jestClientHelper);
}