本文整理汇总了Java中org.elasticsearch.action.search.SearchRequestBuilder.get方法的典型用法代码示例。如果您正苦于以下问题:Java SearchRequestBuilder.get方法的具体用法?Java SearchRequestBuilder.get怎么用?Java SearchRequestBuilder.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.elasticsearch.action.search.SearchRequestBuilder
的用法示例。
在下文中一共展示了SearchRequestBuilder.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: 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());
}
示例2: 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());
}
}
示例3: 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;
}
示例4: selectMatchAll
import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
public String selectMatchAll(String indexs,String types,String field,String value){
try {
if(client==null){
init();
}
SearchRequestBuilder request = client.prepareSearch(indexs.split(",")).setTypes(types.split(","));
request.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
request.setQuery(QueryBuilders.matchQuery(field, value));
request.highlighter(new HighlightBuilder().field(field));
request.addAggregation(AggregationBuilders.terms("data").field(field+".keyword"));
request.setExplain(false);
SearchResponse response = request.get();
return response.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
示例5: selectTermAll
import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
public String selectTermAll(String indexs,String types,String field,String value){
try {
if(client==null){
init();
}
SearchRequestBuilder request = client.prepareSearch(indexs.split(",")).setTypes(types.split(","));
request.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
request.setQuery(QueryBuilders.termQuery(field, value));
request.highlighter(new HighlightBuilder().field(field));
request.addAggregation(AggregationBuilders.terms("data").field(field+".keyword"));
request.setExplain(false);
SearchResponse response = request.get();
return response.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
示例6: 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);
}
示例7: testStringSpecialValueVariable
import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
public void testStringSpecialValueVariable() throws Exception {
// i.e. expression script for term aggregations, which is not allowed
assertAcked(client().admin().indices().prepareCreate("test")
.addMapping("doc", "text", "type=keyword").get());
ensureGreen("test");
indexRandom(true,
client().prepareIndex("test", "doc", "1").setSource("text", "hello"),
client().prepareIndex("test", "doc", "2").setSource("text", "goodbye"),
client().prepareIndex("test", "doc", "3").setSource("text", "hello"));
SearchRequestBuilder req = client().prepareSearch().setIndices("test");
req.setQuery(QueryBuilders.matchAllQuery())
.addAggregation(
AggregationBuilders.terms("term_agg").field("text")
.script(
new Script(ScriptType.INLINE, ExpressionScriptEngineService.NAME, "_value", Collections.emptyMap())));
String message;
try {
// shards that don't have docs with the "text" field will not fail,
// so we may or may not get a total failure
SearchResponse rsp = req.get();
assertThat(rsp.getShardFailures().length, greaterThan(0)); // at least the shards containing the docs should have failed
message = rsp.getShardFailures()[0].reason();
} catch (SearchPhaseExecutionException e) {
message = e.toString();
}
assertThat(message + "should have contained ScriptException",
message.contains("ScriptException"), equalTo(true));
assertThat(message + "should have contained text variable error",
message.contains("text variable"), equalTo(true));
}
示例8: assertSearchFromWithSortValues
import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的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();
}
}
示例9: testMultipleRescores
import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
public void testMultipleRescores() throws Exception {
int numDocs = indexRandomNumbers("keyword", 1, true);
QueryRescorerBuilder eightIsGreat = RescoreBuilder
.queryRescorer(QueryBuilders.functionScoreQuery(QueryBuilders.termQuery("field1", English.intToEnglish(8)),
ScoreFunctionBuilders.weightFactorFunction(1000.0f)).boostMode(CombineFunction.REPLACE))
.setScoreMode(QueryRescoreMode.Total);
QueryRescorerBuilder sevenIsBetter = RescoreBuilder
.queryRescorer(QueryBuilders.functionScoreQuery(QueryBuilders.termQuery("field1", English.intToEnglish(7)),
ScoreFunctionBuilders.weightFactorFunction(10000.0f)).boostMode(CombineFunction.REPLACE))
.setScoreMode(QueryRescoreMode.Total);
// First set the rescore window large enough that both rescores take effect
SearchRequestBuilder request = client().prepareSearch();
request.addRescorer(eightIsGreat, numDocs).addRescorer(sevenIsBetter, numDocs);
SearchResponse response = request.get();
assertFirstHit(response, hasId("7"));
assertSecondHit(response, hasId("8"));
// Now squash the second rescore window so it never gets to see a seven
response = request.setSize(1).clearRescorers().addRescorer(eightIsGreat, numDocs).addRescorer(sevenIsBetter, 1).get();
assertFirstHit(response, hasId("8"));
// We have no idea what the second hit will be because we didn't get a chance to look for seven
// Now use one rescore to drag the number we're looking for into the window of another
QueryRescorerBuilder ninetyIsGood = RescoreBuilder.queryRescorer(QueryBuilders
.functionScoreQuery(QueryBuilders.queryStringQuery("*ninety*"), ScoreFunctionBuilders.weightFactorFunction(1000.0f))
.boostMode(CombineFunction.REPLACE)).setScoreMode(QueryRescoreMode.Total);
QueryRescorerBuilder oneToo = RescoreBuilder.queryRescorer(QueryBuilders
.functionScoreQuery(QueryBuilders.queryStringQuery("*one*"), ScoreFunctionBuilders.weightFactorFunction(1000.0f))
.boostMode(CombineFunction.REPLACE)).setScoreMode(QueryRescoreMode.Total);
request.clearRescorers().addRescorer(ninetyIsGood, numDocs).addRescorer(oneToo, 10);
response = request.setSize(2).get();
assertThat(response.getHits().getMaxScore(), equalTo(response.getHits().getHits()[0].getScore()));
assertFirstHit(response, hasId("91"));
assertFirstHit(response, hasScore(2001.0f));
assertSecondHit(response, hasScore(1001.0f)); // Not sure which one it is but it is ninety something
}
示例10: testHighlightUsesHighlightQuery
import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
public void testHighlightUsesHighlightQuery() throws IOException {
assertAcked(prepareCreate("test").addMapping("type1", "text",
"type=text," + randomStoreField() + "term_vector=with_positions_offsets,index_options=offsets"));
ensureGreen();
index("test", "type1", "1", "text", "Testing the highlight query feature");
refresh();
for (String type : ALL_TYPES) {
HighlightBuilder.Field field = new HighlightBuilder.Field("text");
HighlightBuilder highlightBuilder = new HighlightBuilder().field(field).highlighterType(type);
SearchRequestBuilder search = client().prepareSearch("test").setQuery(QueryBuilders.matchQuery("text", "testing"))
.highlighter(highlightBuilder);
Matcher<String> searchQueryMatcher = equalTo("<em>Testing</em> the highlight query feature");
SearchResponse response = search.get();
assertHighlight(response, 0, "text", 0, searchQueryMatcher);
field = new HighlightBuilder.Field("text");
Matcher<String> hlQueryMatcher = equalTo("Testing the highlight <em>query</em> feature");
field.highlightQuery(matchQuery("text", "query"));
highlightBuilder = new HighlightBuilder().field(field);
search = client().prepareSearch("test").setQuery(QueryBuilders.matchQuery("text", "testing")).highlighter(highlightBuilder);
response = search.get();
assertHighlight(response, 0, "text", 0, hlQueryMatcher);
// Make sure the highlightQuery is taken into account when it is set on the highlight context instead of the field
highlightBuilder.highlightQuery(matchQuery("text", "query"));
field.highlighterType(type).highlightQuery(null);
response = search.get();
assertHighlight(response, 0, "text", 0, hlQueryMatcher);
}
}
示例11: testScriptFields
import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
public void testScriptFields() throws Exception {
assertAcked(prepareCreate("index").addMapping("type",
"s", "type=keyword",
"l", "type=long",
"d", "type=double",
"ms", "type=keyword",
"ml", "type=long",
"md", "type=double").get());
final int numDocs = randomIntBetween(3, 8);
List<IndexRequestBuilder> reqs = new ArrayList<>();
for (int i = 0; i < numDocs; ++i) {
reqs.add(client().prepareIndex("index", "type", Integer.toString(i)).setSource(
"s", Integer.toString(i),
"ms", new String[] {Integer.toString(i), Integer.toString(i+1)},
"l", i,
"ml", new long[] {i, i+1},
"d", i,
"md", new double[] {i, i+1}));
}
indexRandom(true, reqs);
ensureSearchable();
SearchRequestBuilder req = client().prepareSearch("index");
for (String field : Arrays.asList("s", "ms", "l", "ml", "d", "md")) {
req.addScriptField(field,
new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['" + field + "'].values", Collections.emptyMap()));
}
SearchResponse resp = req.get();
assertSearchResponse(resp);
for (SearchHit hit : resp.getHits().getHits()) {
final int id = Integer.parseInt(hit.getId());
Map<String, SearchHitField> fields = hit.getFields();
assertThat(fields.get("s").getValues(), equalTo(Collections.<Object> singletonList(Integer.toString(id))));
assertThat(fields.get("l").getValues(), equalTo(Collections.<Object> singletonList((long) id)));
assertThat(fields.get("d").getValues(), equalTo(Collections.<Object> singletonList((double) id)));
assertThat(fields.get("ms").getValues(), equalTo(Arrays.<Object> asList(Integer.toString(id), Integer.toString(id + 1))));
assertThat(fields.get("ml").getValues(), equalTo(Arrays.<Object> asList((long) id, id + 1L)));
assertThat(fields.get("md").getValues(), equalTo(Arrays.<Object> asList((double) id, id + 1d)));
}
}
示例12: query
import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
@SuppressWarnings("rawtypes")
private SearchResponse query(UAVHttpMessage data, QueryBuilder queryBuilder, QueryBuilder postFilter,
List<SortBuilder> sorts) {
String date = data.getRequest("indexdate");
String currentIndex;
if (date != null) {
// 指定index
currentIndex = this.indexMgr.getIndexByDate(date);
}
else {
// current index
currentIndex = this.indexMgr.getCurrentIndex();
}
SearchRequestBuilder srb = client.getClient().prepareSearch(currentIndex)
.setTypes(ThreadAnalysisIndexMgr.JTA_TABLE).setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
int from = DataConvertHelper.toInt(data.getRequest("from"), -1);
int size = DataConvertHelper.toInt(data.getRequest("size"), -1);
if (from != -1 && size != -1) {
srb = srb.setFrom(from).setSize(size);
}
srb.setQuery(queryBuilder);
if (postFilter != null) {
srb.setPostFilter(postFilter);
}
for (SortBuilder sb : sorts) {
srb.addSort(sb);
}
SearchResponse sr = srb.get(TimeValue.timeValueMillis(timeout));
return sr;
}
示例13: scrollOneTimeWithHits
import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
public static SearchResponse scrollOneTimeWithHits(Client client, SearchRequestBuilder requestBuilder, Select originalSelect, int resultSize) {
SearchResponse responseWithHits;SearchRequestBuilder scrollRequest = requestBuilder
.setScroll(new TimeValue(60000))
.setSize(resultSize);
boolean ordered = originalSelect.isOrderdSelect();
if(!ordered) scrollRequest.addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC);
responseWithHits = scrollRequest.get();
//on ordered select - not using SCAN , elastic returns hits on first scroll
//es5.0 elastic always return docs on scan
// if(!ordered) {
// responseWithHits = client.prepareSearchScroll(responseWithHits.getScrollId()).setScroll(new TimeValue(600000)).get();
// }
return responseWithHits;
}
示例14: query
import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
@Override
public Object query(Person person) {
List<Map<String, Object>> result = new ArrayList<>();
try {
BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
if (person.getName() != null) {
// boolBuilder.must(QueryBuilders.matchQuery("name", person.getName()));
boolBuilder.should(QueryBuilders.matchQuery("name", person.getName()));
}
if (person.getIntroduce() != null) {
// boolBuilder.must(QueryBuilders.matchQuery("introduce", person.getIntroduce()));
boolBuilder.should(QueryBuilders.matchQuery("introduce", person.getIntroduce()));
}
//大于age,小于age+10
if (person.getAge() > 0) {
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
rangeQuery.from(person.getAge());
rangeQuery.to(person.getAge() + 10);
boolBuilder.filter(rangeQuery);
}
SearchRequestBuilder builder = transportClient.prepareSearch(index)
.setTypes(type)
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setQuery(boolBuilder)
.setFrom(0)
.setSize(10);
log.info(String.valueOf(builder));
SearchResponse response = builder.get();
response.getHits().forEach((s) -> result.add(s.getSource()));
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage(), e);
}
return result;
}
示例15: delByQuery
import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
protected boolean delByQuery(QueryBuilder builder, Task task) {
BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(indexName, typeName)
.setQuery(builder).setSize(100)
.setScroll(SCROLL_TIMEOUT);
SearchResponse response = searchRequestBuilder.get();
String query = builder.toString();
int num = bulkRequestBuilder.numberOfActions();
while(true) {
for(SearchHit hit:response.getHits()) {
bulkRequestBuilder.add(new DeleteRequest(indexName, typeName, hit.getId()));
if(task!=null)
task.increaseCount();
}
response = client.prepareSearchScroll(response.getScrollId())
.setScroll(SCROLL_TIMEOUT).get();
if(response.getHits().getHits().length == 0) {
if(task!=null)
task.setDescription("按照query:%s 加载数据,已经添加%s条, 准备执行删除...", query, num);
LOG.debug("准备执行删除, query:" + builder.toString());
break;
} else {
if(task!=null)
task.setDescription("按query:%s删除数据, 已添加%s条", query, num);
LOG.debug("删除数据已添加" + num + "条, query:" + query);
}
}
if(num <= 0) {
if(task!=null)
task.setDescription("执行删除时未找到数据, query:", query);
LOG.debug("执行删除时未找到数据,请检查参数,query:" + query);
return false;
}
BulkResponse bulkResponse = bulkRequestBuilder.get();
if(bulkResponse.hasFailures()) {
if(task!=null)
task.setDescription("按query:%s删除部分数据失败,由于%s", query, bulkResponse.buildFailureMessage());
LOG.error("删除部分数据失败, query:" + query + ", 由于 " + bulkResponse.buildFailureMessage());
} else {
if(task!=null)
task.setDescription("删除数据成功, query:%s, 耗时:%sms", query, bulkResponse.getTookInMillis());
LOG.error("删除数据成功, query:" + query + ", 耗时:" + bulkResponse.getTookInMillis() + "ms");
}
return bulkResponse.hasFailures();
}