本文整理汇总了Java中org.elasticsearch.search.SearchHits类的典型用法代码示例。如果您正苦于以下问题:Java SearchHits类的具体用法?Java SearchHits怎么用?Java SearchHits使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SearchHits类属于org.elasticsearch.search包,在下文中一共展示了SearchHits类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: wildcardQuery
import org.elasticsearch.search.SearchHits; //导入依赖的package包/类
/**
* wildcard查询/or条件/and条件
*/
public static void wildcardQuery() {
try {
Settings settings = Settings.settingsBuilder().put("cluster.name", "elasticsearch1").build();
TransportClient transportClient = TransportClient.builder().
settings(settings).build().addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName("172.16.2.94"), 9300));
SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch("sqd.es_start");
// {"query": {"bool": {"must": [{"or": [{"wildcard": {"content": "*oracle*"}},{"wildcard": {"content": "*mysql*"}}]}],"must_not": [],"should": []}},"from": 0, "size": 10, "sort": [],"aggs": {}}
SearchResponse searchResponse = searchRequestBuilder.
setQuery(QueryBuilders.boolQuery()
.must(QueryBuilders.orQuery(QueryBuilders.wildcardQuery("content","*mysql*"),
QueryBuilders.wildcardQuery("content","*oracle*")))
.must(QueryBuilders.termQuery("tbool","false")))
.setFrom(0).setSize(100).setExplain(true).execute().actionGet();
SearchHits searchHits = searchResponse.getHits();
System.out.println();
System.out.println("Total Hits is " + searchHits.totalHits());
System.out.println();
for (int i = 0; i < searchHits.getHits().length; ++i) {
System.out.println("content is "
+ searchHits.getHits()[i].getSource().get("content"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
示例2: multisearch
import org.elasticsearch.search.SearchHits; //导入依赖的package包/类
/**
* 多字段查询
*/
public static void multisearch() {
try {
Settings settings = Settings.settingsBuilder().put("cluster.name", "elasticsearch1").build();
TransportClient transportClient = TransportClient.builder().
settings(settings).build().addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName("172.16.2.93"), 9300));
SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch("service2","clients");
SearchResponse searchResponse = searchRequestBuilder.
setQuery(QueryBuilders.boolQuery()
.should(QueryBuilders.termQuery("id","5"))
.should(QueryBuilders.prefixQuery("content","oracle")))
.setFrom(0).setSize(100).setExplain(true).execute().actionGet();
SearchHits searchHits = searchResponse.getHits();
System.out.println();
System.out.println("Total Hits is " + searchHits.totalHits());
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
}
示例3: dateSearchBraces
import org.elasticsearch.search.SearchHits; //导入依赖的package包/类
@Test
public void dateSearchBraces() throws IOException, SqlParseException, SQLFeatureNotSupportedException, ParseException {
DateTimeFormatter formatter = DateTimeFormat.forPattern(TS_DATE_FORMAT);
DateTime dateToCompare = new DateTime(2015, 3, 15, 0, 0, 0);
SearchHits response = query(String.format("SELECT odbc_time FROM %s/odbc WHERE odbc_time < {ts '2015-03-15 00:00:00.000'}", TEST_INDEX));
SearchHit[] hits = response.getHits();
for(SearchHit hit : hits) {
Map<String, Object> source = hit.getSource();
String insertTimeStr = (String) source.get("odbc_time");
insertTimeStr = insertTimeStr.replace("{ts '", "").replace("'}", "");
DateTime insertTime = formatter.parseDateTime(insertTimeStr);
String errorMessage = String.format("insert_time must be smaller then 2015-03-15. found: %s", insertTime);
Assert.assertTrue(errorMessage, insertTime.isBefore(dateToCompare));
}
}
示例4: searchAll
import org.elasticsearch.search.SearchHits; //导入依赖的package包/类
/**
* This method Search the document
*/
@Override
public void searchAll() {
SearchHits hits = null;
try {
client = ESclient.getInstant();
SearchResponse response = client.prepareSearch("school", "college")
.setQuery(QueryBuilders.matchAllQuery())
.setExplain(true)
.execute()
.actionGet();
log.info("SearchResponse : " + response);
} catch (Exception ex) {
log.error("Exception occurred while Search All : " + ex, ex);
}
}
示例5: ElasticsearchGraphQueryIterable
import org.elasticsearch.search.SearchHits; //导入依赖的package包/类
public ElasticsearchGraphQueryIterable(
ElasticsearchSearchQueryBase query,
SearchResponse searchResponse,
QueryParameters parameters,
Iterable<T> iterable,
boolean evaluateQueryString,
boolean evaluateHasContainers,
boolean evaluateSortContainers,
long totalHits,
long searchTimeInNanoSeconds,
SearchHits hits
) {
super(parameters, iterable, evaluateQueryString, evaluateHasContainers, evaluateSortContainers);
this.totalHits = totalHits;
this.searchTimeInNanoSeconds = searchTimeInNanoSeconds;
if (hits != null) {
for (SearchHit hit : hits.getHits()) {
scores.put(ElasticsearchDocIdUtils.fromSearchHit(hit), (double) hit.getScore());
}
}
this.aggregationResults = getAggregationResults(query, searchResponse);
}
示例6: createIterable
import org.elasticsearch.search.SearchHits; //导入依赖的package包/类
protected <T> ElasticsearchGraphQueryIterable<T> createIterable(
SearchResponse response,
QueryParameters filterParameters,
Iterable<T> MemgraphObjects,
boolean evaluateQueryString,
boolean evaluateHasContainers,
boolean evaluateSortContainers,
long searchTimeInMillis,
SearchHits hits
) {
return new ElasticsearchGraphQueryIterable<>(
this,
response,
filterParameters,
MemgraphObjects,
evaluateQueryString,
evaluateHasContainers,
evaluateSortContainers,
hits.getTotalHits(),
searchTimeInMillis * 1000000,
hits
);
}
示例7: getSearchResponse
import org.elasticsearch.search.SearchHits; //导入依赖的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;
}
示例8: searchProducts
import org.elasticsearch.search.SearchHits; //导入依赖的package包/类
/**
* Search Product by keywords.
*
* @param request search request which contains keyword and limit
* @return SearchProductsResponse
*/
public SearchProductsResponse searchProducts(SearchProductsRequest request) throws InvalidProtocolBufferException {
QueryBuilder queryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery("productName", request.getKeyWord()));
SearchResponse response = esClient.prepareSearch(INDEX)
.setTypes(TYPE)
.setQuery(queryBuilder)
.setSize(request.getLimit())
.execute()
.actionGet();
SearchHits hits = response.getHits();
SearchProductsResponse.Builder responseBuilder = SearchProductsResponse.newBuilder();
for (SearchHit hit : hits) {
Product.Builder builder = Product.newBuilder();
jsonParser.merge(hit.getSourceAsString(), builder);
responseBuilder.addProducts(builder.build());
}
return responseBuilder.build();
}
示例9: assertEquivalent
import org.elasticsearch.search.SearchHits; //导入依赖的package包/类
private static void assertEquivalent(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[] rHits = rightHits.getHits();
Arrays.sort(hits, searchHitsComparator);
Arrays.sort(rHits, searchHitsComparator);
for (int i = 0; i < hits.length; i++) {
assertThat("query: " + query, hits[i].getScore(), equalTo(rHits[i].getScore()));
}
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: " + query,hits[i].getId(), equalTo(rHits[i].getId()));
}
}
示例10: assertEquivalentOrSubstringMatch
import org.elasticsearch.search.SearchHits; //导入依赖的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()));
}
}
}
示例11: queryToList
import org.elasticsearch.search.SearchHits; //导入依赖的package包/类
/**
*
* @param data
* @param queryBuilder
* @param postFilter
*/
@SuppressWarnings("rawtypes")
private void queryToList(UAVHttpMessage data, QueryBuilder queryBuilder, QueryBuilder postFilter,
SortBuilder[] sorts) {
SearchResponse sr = query(data, queryBuilder, postFilter, sorts);
SearchHits shits = sr.getHits();
List<Map<String, Object>> records = new ArrayList<Map<String, Object>>();
for (SearchHit sh : shits) {
Map<String, Object> record = sh.getSourceAsMap();
if (record == null) {
continue;
}
records.add(record);
}
data.putResponse("rs", JSONHelper.toString(records));
// 返回总的条数
data.putResponse("count", shits.getTotalHits() + "");
}
示例12: findUrlsByStatusAndSource
import org.elasticsearch.search.SearchHits; //导入依赖的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());
}
示例13: testConvertToIdsList
import org.elasticsearch.search.SearchHits; //导入依赖的package包/类
@Test
public void testConvertToIdsList() {
// Test data
final SearchResponse searchResponse = createMock(SearchResponse.class);
final SearchHits searchHits = createMock(SearchHits.class);
final SearchHit searchHit1 = createMock(SearchHit.class);
final SearchHit searchHit2 = createMock(SearchHit.class);
final SearchHit[] searchHitsArray = new SearchHit[]{searchHit1, searchHit2};
final String searchHit1Id = "search hit 1 id";
final String searchHit2Id = "search hit 1 id";
// Reset
resetAll();
// Expectations
expect(searchResponse.getHits()).andReturn(searchHits);
expect(searchHits.getHits()).andReturn(searchHitsArray);
expect(searchHit1.getId()).andReturn(searchHit1Id);
expect(searchHit2.getId()).andReturn(searchHit2Id);
// Replay
replayAll();
// Run test scenario
final List<String> response = searchResponseComponent.convertToIdsList(searchResponse);
// Verify
verifyAll();
assertEquals(Arrays.asList(searchHit1Id, searchHit2Id), response);
}
示例14: greaterThanOrEqualTest
import org.elasticsearch.search.SearchHits; //导入依赖的package包/类
@Test
public void greaterThanOrEqualTest() throws IOException, SqlParseException, SQLFeatureNotSupportedException {
int someAge = 25;
SearchHits response = query(String.format("SELECT * FROM %s WHERE age >= %s LIMIT 1000", TEST_INDEX, someAge));
SearchHit[] hits = response.getHits();
boolean isEqualFound = false;
for(SearchHit hit : hits) {
int age = (int) hit.getSource().get("age");
assertThat(age, greaterThanOrEqualTo(someAge));
if(age == someAge)
isEqualFound = true;
}
Assert.assertTrue(String.format("at least one of the documents need to contains age equal to %s", someAge), isEqualFound);
}
示例15: executeAndFillSubQuery
import org.elasticsearch.search.SearchHits; //导入依赖的package包/类
private static void executeAndFillSubQuery(Client client , SubQueryExpression subQueryExpression,QueryAction queryAction) throws SqlParseException {
List<Object> values = new ArrayList<>();
Object queryResult;
try {
queryResult = QueryActionElasticExecutor.executeAnyAction(client,queryAction);
} catch (Exception e) {
throw new SqlParseException("could not execute SubQuery: " + e.getMessage());
}
String returnField = subQueryExpression.getReturnField();
if(queryResult instanceof SearchHits) {
SearchHits hits = (SearchHits) queryResult;
for (SearchHit hit : hits) {
values.add(ElasticResultHandler.getFieldValue(hit,returnField));
}
}
else {
throw new SqlParseException("on sub queries only support queries that return Hits and not aggregations");
}
subQueryExpression.setValues(values.toArray());
}