Java源码示例:io.searchbox.core.SearchResult
示例1
@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();
}
示例2
@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;
}
示例3
@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;
}
示例4
@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());
}
示例5
@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");
}
示例6
@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;
}
示例7
@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;
}
示例8
@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");
}
示例9
/**
* 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");
}
示例10
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");
}
示例11
/**
* 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;
}
示例12
/**
* 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);
}
示例13
@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());
}
示例14
@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()));
}
示例15
@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);
}
示例16
@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);
}
示例17
@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);
}
示例18
@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);
}
示例19
@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);
}
示例20
@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);
}
示例21
@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);
}
示例22
@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);
}
示例23
@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();
}
示例24
@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);
}
示例25
@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);
}
示例26
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);
}
}
示例27
@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);
}
}
示例28
/**
* ES 执行查询结果
* @param query
* @return
*/
private SearchBookResult getSearchResult(String query){
SearchBookResult result = new SearchBookResult();
// 封装查询对象
Search search = new Search.Builder(query)
.addIndex(aliasName)
.addType(indexType).build();
// 执行查询
try {
SearchResult searchResult = this.jestClient.execute(search);
List<SearchBookItem> bookList;
if (searchResult.isSucceeded()) {
// 查询成功,处理结果项
List<SearchResult.Hit<SearchBookItem, Void>> hitList = searchResult.getHits(SearchBookItem.class);
bookList = new ArrayList<>(hitList.size());
for (SearchResult.Hit<SearchBookItem, Void> hit : hitList) {
bookList.add(hit.source);
}
} else {
bookList = new ArrayList<>();
}
// 赋值
result.setTotal(searchResult.getTotal());
result.setBookList(bookList);
} catch (IOException e) {
LOGGER.error("查询图书异常,查询语句:{}", query, e);
}
return result;
}
示例29
@Override
public <T> WSearchResult<T> searchObj(String index, String type, SearchQuery query, Class<T> cls) throws
Exception {
Search.Builder builder = new Search.Builder(convert.toText(query));
if (index != null) {
builder.addIndex(index);
}
if (type != null) {
builder.addType(type);
}
SearchResult result = _exec(builder.build());
if (result != null) {
WSearchResult<T> wresult = new WSearchResult<>();
WSearchResultHits<T> hits = new WSearchResultHits<>();
hits.setTotal(result.getTotal());
List<SearchResult.Hit<T, Void>> allHist = result.getHits(cls);
List<WEsDoc<T>> data = new ArrayList<>();
for (SearchResult.Hit<T, Void> hit : allHist) {
WEsDoc<T> doc = new WEsDoc<>();
doc.setIndex(hit.index);
doc.setType(hit.type);
doc.setIndex(hit.index);
doc.setSource(hit.source);
doc.setScore(hit.score);
data.add(doc);
}
hits.setHits(data);
wresult.setHits(hits);
return wresult;
}
return null;
}
示例30
/**
* Map results from elasticsearch to document revisions
*
* @param searchResult
* @param documentSearchQuery
* @return
*/
public List<DocumentRevision> processSearchResult(SearchResult searchResult, DocumentSearchQuery documentSearchQuery) {
List<SearchResult.Hit<Map, Void>> hits = searchResult.getHits(Map.class);
Set<DocumentIterationKey> documentIterationKeys = new HashSet<>();
if (hits != null) {
for (SearchResult.Hit<Map, Void> hit : hits) {
Map<?, ?> source = hit.source;
documentIterationKeys.add(getDocumentIterationKey(source));
}
}
LOGGER.log(Level.INFO, "Results: " + documentIterationKeys.size());
return documentIterationKeysToDocumentRevisions(documentSearchQuery.isFetchHeadOnly(), documentIterationKeys);
}