本文整理匯總了Java中org.elasticsearch.action.search.SearchRequestBuilder類的典型用法代碼示例。如果您正苦於以下問題:Java SearchRequestBuilder類的具體用法?Java SearchRequestBuilder怎麽用?Java SearchRequestBuilder使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
SearchRequestBuilder類屬於org.elasticsearch.action.search包,在下文中一共展示了SearchRequestBuilder類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: multisearch
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的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();
}
}
示例2: assertStoredBinaryFields
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的package包/類
/**
* Make sure we can load stored binary fields.
*/
void assertStoredBinaryFields(String indexName, Version version) throws Exception {
SearchRequestBuilder builder = client().prepareSearch(indexName);
builder.setQuery(QueryBuilders.matchAllQuery());
builder.setSize(100);
builder.addStoredField("binary");
SearchHits hits = builder.get().getHits();
assertEquals(100, hits.getHits().length);
for(SearchHit hit : hits) {
SearchHitField field = hit.field("binary");
assertNotNull(field);
Object value = field.getValue();
assertTrue(value instanceof BytesArray);
assertEquals(16, ((BytesArray) value).length());
}
}
示例3: wildcardQuery
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的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();
}
}
示例4: testScore
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的package包/類
public void testScore() throws Exception {
createIndex("test");
ensureGreen("test");
indexRandom(true,
client().prepareIndex("test", "doc", "1").setSource("text", "hello goodbye"),
client().prepareIndex("test", "doc", "2").setSource("text", "hello hello hello goodbye"),
client().prepareIndex("test", "doc", "3").setSource("text", "hello hello goodebye"));
ScoreFunctionBuilder<?> score = ScoreFunctionBuilders.scriptFunction(new Script(ScriptType.INLINE, "expression", "1 / _score", Collections.emptyMap()));
SearchRequestBuilder req = client().prepareSearch().setIndices("test");
req.setQuery(QueryBuilders.functionScoreQuery(QueryBuilders.termQuery("text", "hello"), score).boostMode(CombineFunction.REPLACE));
req.setSearchType(SearchType.DFS_QUERY_THEN_FETCH); // make sure DF is consistent
SearchResponse rsp = req.get();
assertSearchResponse(rsp);
SearchHits hits = rsp.getHits();
assertEquals(3, hits.getTotalHits());
assertEquals("1", hits.getAt(0).getId());
assertEquals("3", hits.getAt(1).getId());
assertEquals("2", hits.getAt(2).getId());
}
示例5: testDocIdSort
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的package包/類
public void testDocIdSort() throws Exception {
int numShards = setupIndex(true);
SearchResponse sr = client().prepareSearch("test")
.setQuery(matchAllQuery())
.setSize(0)
.get();
int numDocs = (int) sr.getHits().getTotalHits();
assertThat(numDocs, equalTo(NUM_DOCS));
int max = randomIntBetween(2, numShards*3);
for (String field : new String[]{"_uid", "random_int", "static_int"}) {
int fetchSize = randomIntBetween(10, 100);
SearchRequestBuilder request = client().prepareSearch("test")
.setQuery(matchAllQuery())
.setScroll(new Scroll(TimeValue.timeValueSeconds(10)))
.setSize(fetchSize)
.addSort(SortBuilders.fieldSort("_doc"));
assertSearchSlicesWithScroll(request, field, max);
}
}
示例6: phraseBoostTestCaseForClauses
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的package包/類
private <P extends AbstractQueryBuilder<P>> void
phraseBoostTestCaseForClauses(String highlighterType, float boost, QueryBuilder terms, P phrase) {
Matcher<String> highlightedMatcher = Matchers.either(containsString("<em>highlight words together</em>")).or(
containsString("<em>highlight</em> <em>words</em> <em>together</em>"));
SearchRequestBuilder search = client().prepareSearch("test").highlighter(
new HighlightBuilder().field("field1", 100, 1).order("score").highlighterType(highlighterType).requireFieldMatch(true));
// Try with a bool query
phrase.boost(boost);
SearchResponse response = search.setQuery(boolQuery().must(terms).should(phrase)).get();
assertHighlight(response, 0, "field1", 0, 1, highlightedMatcher);
phrase.boost(1);
// Try with a boosting query
response = search.setQuery(boostingQuery(phrase, terms).boost(boost).negativeBoost(1)).get();
assertHighlight(response, 0, "field1", 0, 1, highlightedMatcher);
// Try with a boosting query using a negative boost
response = search.setQuery(boostingQuery(phrase, terms).boost(1).negativeBoost(1/boost)).get();
assertHighlight(response, 0, "field1", 0, 1, highlightedMatcher);
}
示例7: assertBasicSearchWorks
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的package包/類
void assertBasicSearchWorks(String indexName) {
logger.info("--> testing basic search");
SearchRequestBuilder searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.matchAllQuery());
SearchResponse searchRsp = searchReq.get();
ElasticsearchAssertions.assertNoFailures(searchRsp);
long numDocs = searchRsp.getHits().getTotalHits();
logger.info("Found {} in old index", numDocs);
logger.info("--> testing basic search with sort");
searchReq.addSort("long_sort", SortOrder.ASC);
ElasticsearchAssertions.assertNoFailures(searchReq.get());
logger.info("--> testing exists filter");
searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.existsQuery("string"));
searchRsp = searchReq.get();
ElasticsearchAssertions.assertNoFailures(searchRsp);
assertEquals(numDocs, searchRsp.getHits().getTotalHits());
GetSettingsResponse getSettingsResponse = client().admin().indices().prepareGetSettings(indexName).get();
Version versionCreated = Version.fromId(Integer.parseInt(getSettingsResponse.getSetting(indexName, "index.version.created")));
if (versionCreated.onOrAfter(Version.V_2_4_0)) {
searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.existsQuery("field.with.dots"));
searchRsp = searchReq.get();
ElasticsearchAssertions.assertNoFailures(searchRsp);
assertEquals(numDocs, searchRsp.getHits().getTotalHits());
}
}
示例8: selectAll
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的package包/類
public String selectAll(String indexs,String types,String condition){
try {
if(client==null){
init();
}
SearchRequestBuilder request = client.prepareSearch(indexs.split(",")).setTypes(types.split(","));
request.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
request.setQuery(QueryBuilders.queryStringQuery(condition));
request.setExplain(false);
SearchResponse response = request.get();
return response.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
示例9: deleteExtendedDataForElement
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的package包/類
private void deleteExtendedDataForElement(Element element) {
try {
QueryBuilder filter = QueryBuilders.termQuery(EXTENDED_DATA_ELEMENT_ID_FIELD_NAME, element.getId());
SearchRequestBuilder s = getClient().prepareSearch(getIndicesToQuery())
.setTypes(ELEMENT_TYPE)
.setQuery(QueryBuilders.boolQuery().must(QueryBuilders.matchAllQuery()).filter(filter))
.storedFields(
EXTENDED_DATA_ELEMENT_ID_FIELD_NAME,
EXTENDED_DATA_TABLE_NAME_FIELD_NAME,
EXTENDED_DATA_TABLE_ROW_ID_FIELD_NAME
);
for (SearchHit hit : s.execute().get().getHits()) {
if (MUTATION_LOGGER.isTraceEnabled()) {
LOGGER.trace("deleting extended data document %s", hit.getId());
}
getClient().prepareDelete(hit.getIndex(), ELEMENT_TYPE, hit.getId()).execute().actionGet();
}
} catch (Exception ex) {
throw new MemgraphException("Could not delete extended data for element: " + element.getId());
}
}
示例10: addPagingAndSortingToSearchRequest
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的package包/類
/**
* add the sort order to the request searchRequestBuilder
* if the frontend send sort with "path : desc". It should be converted to "path.raw" : {"order" : "desc" }
* https://www.elastic.co/guide/en/elasticsearch/guide/current/multi-fields.html#multi-fields
*
* @param pageable
* @param searchRequestBuilder
*/
private void addPagingAndSortingToSearchRequest(Pageable pageable, SearchRequestBuilder searchRequestBuilder) {
//par défaut, renvoi la première page trié sur le _score ou le _doc, si rien n'est spécifié
//effectue le tri
if (pageable != null) {
searchRequestBuilder
.setFrom(pageable.getOffset())
.setSize(pageable.getPageSize());
if (pageable.getSort() != null) {
pageable.getSort().forEach(
order -> searchRequestBuilder.addSort(
Constants.ORDER_FIELD_MAPPING.get(order.getProperty()),
SortOrder.valueOf(order.getDirection().name()))
);
}
}
}
示例11: getSearchResponse
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的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;
}
示例12: explanFields
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的package包/類
private void explanFields(SearchRequestBuilder request, List<Field> fields, AggregationBuilder groupByAgg) throws SqlParseException {
for (Field field : fields) {
if (field instanceof MethodField) {
if (field.getName().equals("script")) {
request.addStoredField(field.getAlias());
DefaultQueryAction defaultQueryAction = new DefaultQueryAction(client, select);
defaultQueryAction.intialize(request);
List<Field> tempFields = Lists.newArrayList(field);
defaultQueryAction.setFields(tempFields);
continue;
}
AggregationBuilder makeAgg = aggMaker.makeFieldAgg((MethodField) field, groupByAgg);
if (groupByAgg != null) {
groupByAgg.subAggregation(makeAgg);
} else {
request.addAggregation(makeAgg);
}
} else if (field instanceof Field) {
request.addStoredField(field.getName());
} else {
throw new SqlParseException("it did not support this field method " + field);
}
}
}
示例13: customfindAll
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的package包/類
/**
* Return all records, and truncate the content with the ResultTruncatedContentMapper
*
* @param pageable
* @param version
* @param project
* @return
*/
@Override
public Page<File> customfindAll(Pageable pageable, List<String> version, List<String> project, List<String> extension) {
NativeSearchQueryBuilder nativeSearchQueryBuilder = Queries.constructSearchQueryBuilder("");
NativeSearchQuery nativeSearchQuery = nativeSearchQueryBuilder.build();
SearchRequestBuilder searchRequestBuilder = constructRequestBuilder(nativeSearchQuery, pageable, version, project, extension);
SearchResponse response = searchRequestBuilder.execute().actionGet();
SearchHit[] hits = response.getHits().hits();
ResultTruncatedContentMapper mapper = new ResultTruncatedContentMapper();
return mapper.mapResults(response, File.class, nativeSearchQuery.getPageable());
// }
}
示例14: updateRequestWithHighlight
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的package包/類
protected void updateRequestWithHighlight(Select select, SearchRequestBuilder request) {
boolean foundAnyHighlights = false;
HighlightBuilder highlightBuilder = new HighlightBuilder();
for(Hint hint : select.getHints()){
if(hint.getType() == HintType.HIGHLIGHT){
HighlightBuilder.Field highlightField = parseHighlightField(hint.getParams());
if(highlightField != null){
foundAnyHighlights = true;
highlightBuilder.field(highlightField);
}
}
}
if(foundAnyHighlights){
request.highlighter(highlightBuilder);
}
}
示例15: fetchAllHits
import org.elasticsearch.action.search.SearchRequestBuilder; //導入依賴的package包/類
private List<SearchHit> fetchAllHits(TableInJoinRequestBuilder tableInJoinRequest) {
Integer hintLimit = tableInJoinRequest.getHintLimit();
SearchRequestBuilder requestBuilder = tableInJoinRequest.getRequestBuilder();
if (hintLimit != null && hintLimit < MAX_RESULTS_ON_ONE_FETCH) {
requestBuilder.setSize(hintLimit);
SearchResponse searchResponse = requestBuilder.get();
updateMetaSearchResults(searchResponse);
return Arrays.asList(searchResponse.getHits().getHits());
}
return scrollTillLimit(tableInJoinRequest, hintLimit);
}