本文整理汇总了Java中org.elasticsearch.action.search.SearchResponse.getHits方法的典型用法代码示例。如果您正苦于以下问题:Java SearchResponse.getHits方法的具体用法?Java SearchResponse.getHits怎么用?Java SearchResponse.getHits使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.elasticsearch.action.search.SearchResponse
的用法示例。
在下文中一共展示了SearchResponse.getHits方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: assertEquivalentOrSubstringMatch
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
private static void assertEquivalentOrSubstringMatch(String query, SearchResponse plain, SearchResponse rescored) {
assertNoFailures(plain);
assertNoFailures(rescored);
SearchHits leftHits = plain.getHits();
SearchHits rightHits = rescored.getHits();
assertThat(leftHits.getTotalHits(), equalTo(rightHits.getTotalHits()));
assertThat(leftHits.getHits().length, equalTo(rightHits.getHits().length));
SearchHit[] hits = leftHits.getHits();
SearchHit[] otherHits = rightHits.getHits();
if (!hits[0].getId().equals(otherHits[0].getId())) {
assertThat(((String) otherHits[0].getSourceAsMap().get("field1")).contains(query), equalTo(true));
} else {
Arrays.sort(hits, searchHitsComparator);
Arrays.sort(otherHits, searchHitsComparator);
for (int i = 0; i < hits.length; i++) {
if (hits[i].getScore() == hits[hits.length-1].getScore()) {
return; // we need to cut off here since this is the tail of the queue and we might not have fetched enough docs
}
assertThat(query, hits[i].getId(), equalTo(rightHits.getHits()[i].getId()));
}
}
}
示例2: getSearchResponse
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
private SearchResponse getSearchResponse(EnumSet<ElasticsearchDocumentType> elementType, int skip, int limit, boolean includeAggregations) {
SearchRequestBuilder q = buildQuery(elementType, includeAggregations)
.setFrom(skip)
.setSize(limit);
if (QUERY_LOGGER.isTraceEnabled()) {
QUERY_LOGGER.trace("query: %s", q);
}
SearchResponse searchResponse = q.execute().actionGet();
SearchHits hits = searchResponse.getHits();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"elasticsearch results %d of %d (time: %dms)",
hits.hits().length,
hits.getTotalHits(),
searchResponse.getTookInMillis()
);
}
return searchResponse;
}
示例3: testWildcardQuerySupportsName
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
public void testWildcardQuerySupportsName() {
createIndex("test1");
ensureGreen();
client().prepareIndex("test1", "type1", "1").setSource("title", "title1").get();
refresh();
SearchResponse searchResponse = client().prepareSearch()
.setQuery(QueryBuilders.wildcardQuery("title", "titl*").queryName("wildcard")).get();
assertHitCount(searchResponse, 1L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("wildcard"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
}
示例4: testRegExpQuerySupportsName
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
public void testRegExpQuerySupportsName() {
createIndex("test1");
ensureGreen();
client().prepareIndex("test1", "type1", "1").setSource("title", "title1").get();
refresh();
SearchResponse searchResponse = client().prepareSearch()
.setQuery(QueryBuilders.regexpQuery("title", "title1").queryName("regex")).get();
assertHitCount(searchResponse, 1L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("regex"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
}
示例5: mapResults
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
@Override
public <T> FacetedPageImpl<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
long totalHits = response.getHits().totalHits();
List<T> results = new ArrayList<T>();
for (SearchHit hit : response.getHits()) {
if (hit != null) {
T result = null;
if (StringUtils.isNotBlank(hit.sourceAsString())) {
result = mapEntity(hit.sourceAsString() , hit , clazz);
} else {
result = mapEntity(hit.getFields().values() , hit , clazz);
}
setPersistentEntityId(result, hit.getId(), clazz);
populateScriptFields(result, hit);
results.add(result);
}
}
return new FacetedPageImpl<T>(results, pageable, totalHits);
}
示例6: findUrlsByStatusAndSource
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
public List<HttpUrl> findUrlsByStatusAndSource(Enum status, String source, int count) {
BoolQueryBuilder filter = QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("status", String.valueOf(status)))
.must(QueryBuilders.termQuery("source", source));
SearchResponse response = getConnection().getClient()
.prepareSearch(getIndex())
.setTypes(getType())
.setSearchType(SearchType.DEFAULT)
.setPostFilter(filter)
.addSort("created", SortOrder.DESC)
.setSize(count)
.setFetchSource(true)
.setExplain(false)
.execute()
.actionGet();
SearchHits hits = response.getHits();
return Arrays.stream(hits.getHits())
.map(SearchHit::getSource)
.map(s -> {
HttpUrl httpUrl = new HttpUrl();
httpUrl.setUrl(Objects.toString(s.get("url"), null));
httpUrl.setPublished(Objects.toString(s.get("published"), null));
httpUrl.setDiscovered(EsDataParser.nullOrDate(s.get("created")));
httpUrl.setSource(source);
return httpUrl;
})
.collect(Collectors.toList());
}
示例7: testSimplePolygon
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
public void testSimplePolygon() throws Exception {
List<GeoPoint> points = new ArrayList<>();
points.add(new GeoPoint(40.7, -74.0));
points.add(new GeoPoint(40.7, -74.1));
points.add(new GeoPoint(40.8, -74.1));
points.add(new GeoPoint(40.8, -74.0));
points.add(new GeoPoint(40.7, -74.0));
SearchResponse searchResponse = client().prepareSearch("test") // from NY
.setQuery(boolQuery().must(geoPolygonQuery("location", points)))
.execute().actionGet();
assertHitCount(searchResponse, 4);
assertThat(searchResponse.getHits().getHits().length, equalTo(4));
for (SearchHit hit : searchResponse.getHits()) {
assertThat(hit.getId(), anyOf(equalTo("1"), equalTo("3"), equalTo("4"), equalTo("5")));
}
}
示例8: testSimpleUnclosedPolygon
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
public void testSimpleUnclosedPolygon() throws Exception {
List<GeoPoint> points = new ArrayList<>();
points.add(new GeoPoint(40.7, -74.0));
points.add(new GeoPoint(40.7, -74.1));
points.add(new GeoPoint(40.8, -74.1));
points.add(new GeoPoint(40.8, -74.0));
SearchResponse searchResponse = client().prepareSearch("test") // from NY
.setQuery(boolQuery().must(geoPolygonQuery("location", points))).execute().actionGet();
assertHitCount(searchResponse, 4);
assertThat(searchResponse.getHits().getHits().length, equalTo(4));
for (SearchHit hit : searchResponse.getHits()) {
assertThat(hit.getId(), anyOf(equalTo("1"), equalTo("3"), equalTo("4"), equalTo("5")));
}
}
示例9: deleteES
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
private static void deleteES(Client client) {
BulkRequestBuilder bulkRequest = client.prepareBulk();
SearchResponse response = client.prepareSearch(index).setTypes(type)
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(QueryBuilders.matchAllQuery())
.setFrom(0).setSize(20).setExplain(true).execute().actionGet();
System.out.println("length: " + response.getHits().getHits().length);
if (response.getHits().getHits().length != 0) {
for (SearchHit hit : response.getHits()) {
String id = hit.getId();
System.out.println("id: " + id);
bulkRequest.add(client.prepareDelete(index, type, id).request());
}
BulkResponse bulkResponse = bulkRequest.get();
if (bulkResponse.hasFailures()) {
for (BulkItemResponse item : bulkResponse.getItems()) {
System.out.println(item.getFailureMessage());
}
} else {
System.out.println("delete ok");
}
} else {
System.out.println("delete ok");
}
}
示例10: SearchResult
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
public SearchResult(SearchResponse resp) {
SearchHits hits = resp.getHits();
this.total = hits.getTotalHits();
results = new ArrayList<>(hits.getHits().length);
for (SearchHit searchHit : hits.getHits()) {
if (searchHit.getSource() != null) {
results.add(searchHit.getSource());
} else if (searchHit.getFields() != null) {
Map<String, SearchHitField> fields = searchHit.getFields();
results.add(toFieldsMap(fields));
}
}
}
示例11: useScrollNoParams
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
@Test
public void useScrollNoParams() throws IOException, SqlParseException, SQLFeatureNotSupportedException{
SearchResponse response = getSearchResponse(String.format("SELECT /*! USE_SCROLL*/ age,gender,firstname,balance FROM %s/account LIMIT 2000", TEST_INDEX, TEST_INDEX));
Assert.assertNotNull(response.getScrollId());
SearchHits hits = response.getHits();
//default is 50 , es5.0 functionality now returns docs on first scroll
Assert.assertEquals(50,hits.getHits().length);
Assert.assertEquals(1000,hits.getTotalHits());
}
示例12: searchFacts
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
/**
* Search for Facts indexed in ElasticSearch by a given search criteria. Only Facts satisfying the search criteria
* will be returned. Returns an empty list if no Fact satisfies the search criteria.
* <p>
* Both 'currentUserID' (identifying the calling user) and 'availableOrganizationID' (identifying the Organizations
* the calling user has access to) must be set in the search criteria in order to apply access control to Facts. Only
* Facts accessible to the calling user will be returned.
*
* @param criteria Search criteria to match against Facts
* @return Facts satisfying search Criteria
*/
public List<FactDocument> searchFacts(FactSearchCriteria criteria) {
List<FactDocument> result = ListUtils.list();
if (criteria == null) return result;
SearchResponse response;
try {
response = clientFactory.getHighLevelClient().search(buildSearchRequest(criteria));
} catch (IOException ex) {
throw logAndExit(ex, "Could not perform request to search for Facts.");
}
if (response.status() != RestStatus.OK) {
LOGGER.warning("Could not search for Facts (response code %s).", response.status());
return result;
}
for (SearchHit hit : response.getHits()) {
FactDocument document = decodeFactDocument(UUID.fromString(hit.getId()), toBytes(hit.getSourceRef()));
if (document != null) {
result.add(document);
}
}
LOGGER.info("Successfully retrieved %d Facts.", result.size());
return result;
}
示例13: testSparseField
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
public void testSparseField() throws Exception {
ElasticsearchAssertions.assertAcked(prepareCreate("test").addMapping("doc", "x", "type=long", "y", "type=long"));
ensureGreen("test");
indexRandom(true,
client().prepareIndex("test", "doc", "1").setSource("x", 4),
client().prepareIndex("test", "doc", "2").setSource("y", 2));
SearchResponse rsp = buildRequest("doc['x'] + 1").get();
ElasticsearchAssertions.assertSearchResponse(rsp);
SearchHits hits = rsp.getHits();
assertEquals(2, rsp.getHits().getTotalHits());
assertEquals(5.0, hits.getAt(0).field("foo").getValue(), 0.0D);
assertEquals(1.0, hits.getAt(1).field("foo").getValue(), 0.0D);
}
示例14: assertSearchFromWithSortValues
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
private void assertSearchFromWithSortValues(String indexName, String typeName, List<List> documents, int reqSize) throws Exception {
int numFields = documents.get(0).size();
{
createIndexMappingsFromObjectType(indexName, typeName, documents.get(0));
List<IndexRequestBuilder> requests = new ArrayList<>();
for (int i = 0; i < documents.size(); i++) {
XContentBuilder builder = jsonBuilder();
assertThat(documents.get(i).size(), Matchers.equalTo(numFields));
builder.startObject();
for (int j = 0; j < numFields; j++) {
builder.field("field" + Integer.toString(j), documents.get(i).get(j));
}
builder.endObject();
requests.add(client().prepareIndex(INDEX_NAME, TYPE_NAME, Integer.toString(i)).setSource(builder));
}
indexRandom(true, requests);
}
Collections.sort(documents, LST_COMPARATOR);
int offset = 0;
Object[] sortValues = null;
while (offset < documents.size()) {
SearchRequestBuilder req = client().prepareSearch(indexName);
for (int i = 0; i < documents.get(0).size(); i++) {
req.addSort("field" + Integer.toString(i), SortOrder.ASC);
}
req.setQuery(matchAllQuery()).setSize(reqSize);
if (sortValues != null) {
req.searchAfter(sortValues);
}
SearchResponse searchResponse = req.get();
for (SearchHit hit : searchResponse.getHits()) {
List toCompare = convertSortValues(documents.get(offset++));
assertThat(LST_COMPARATOR.compare(toCompare, Arrays.asList(hit.getSortValues())), equalTo(0));
}
sortValues = searchResponse.getHits().getHits()[searchResponse.getHits().getHits().length-1].getSortValues();
}
}
示例15: testMatchedWithShould
import org.elasticsearch.action.search.SearchResponse; //导入方法依赖的package包/类
/**
* Test case for issue #4361: https://github.com/elastic/elasticsearch/issues/4361
*/
public void testMatchedWithShould() throws Exception {
createIndex("test");
ensureGreen();
client().prepareIndex("test", "type1", "1").setSource("content", "Lorem ipsum dolor sit amet").get();
client().prepareIndex("test", "type1", "2").setSource("content", "consectetur adipisicing elit").get();
refresh();
// Execute search at least two times to load it in cache
int iter = scaledRandomIntBetween(2, 10);
for (int i = 0; i < iter; i++) {
SearchResponse searchResponse = client().prepareSearch()
.setQuery(
boolQuery()
.minimumShouldMatch(1)
.should(queryStringQuery("dolor").queryName("dolor"))
.should(queryStringQuery("elit").queryName("elit"))
)
.setPreference("_primary")
.get();
assertHitCount(searchResponse, 2L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("dolor"));
} else if (hit.getId().equals("2")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("elit"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
}
}