本文整理汇总了Java中org.elasticsearch.index.query.QueryBuilder类的典型用法代码示例。如果您正苦于以下问题:Java QueryBuilder类的具体用法?Java QueryBuilder怎么用?Java QueryBuilder使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
QueryBuilder类属于org.elasticsearch.index.query包,在下文中一共展示了QueryBuilder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: randomTerminalQuery
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的package包/类
private static QueryBuilder randomTerminalQuery(List<String> stringFields, List<String> numericFields, int numDocs) {
switch (randomIntBetween(0,6)) {
case 0:
return randomTermQuery(stringFields, numDocs);
case 1:
return randomTermsQuery(stringFields, numDocs);
case 2:
return randomRangeQuery(numericFields, numDocs);
case 3:
return QueryBuilders.matchAllQuery();
case 4:
return randomCommonTermsQuery(stringFields, numDocs);
case 5:
return randomFuzzyQuery(stringFields);
case 6:
return randomIDsQuery();
default:
return randomTermQuery(stringFields, numDocs);
}
}
示例2: urlParamsToQueryBuilder
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的package包/类
public static QueryBuilder urlParamsToQueryBuilder(RestRequest request) {
String queryString = request.param("q");
if (queryString == null) {
return null;
}
QueryStringQueryBuilder queryBuilder = QueryBuilders.queryStringQuery(queryString);
queryBuilder.defaultField(request.param("df"));
queryBuilder.analyzer(request.param("analyzer"));
queryBuilder.analyzeWildcard(request.paramAsBoolean("analyze_wildcard", false));
queryBuilder.lenient(request.paramAsBoolean("lenient", null));
String defaultOperator = request.param("default_operator");
if (defaultOperator != null) {
queryBuilder.defaultOperator(Operator.fromString(defaultOperator));
}
return queryBuilder;
}
示例3: listTopicsByURL
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的package包/类
@Override
public IResult listTopicsByURL(String url, ITicket credentials) {
QueryBuilder qb1 = QueryBuilders.termQuery(ITQCoreOntology.RESOURCE_URL_PROPERTY, url);
IResult result = topicMap.runQuery(qb1.toString(), 0, -1, credentials);
environment.logDebug("TopicMapModel.listTopicsByURL+ "+result.getErrorString()+" | "+result.getResultObject());
//TopicMapModel.getTopicByURL+ | [[email protected], [email protected]]
List<Object> lx = (List<Object>)result.getResultObject();
if (lx != null) {
if (lx.size() > 0) {
try {
ISubjectProxy n = (SubjectProxy)(lx.get(0));
result.setResultObject(n);
} catch (Exception ex) {
environment.logError(ex.getMessage(), ex);
result.addErrorString(ex.getMessage());
result.setResultObject(null);
}
} else
result.setResultObject(null);
}
System.out.println("LISTTOPICSBYURL+ "+result.getErrorString()+" | "+result.getResultObject());
return result;
}
示例4: createConfig
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的package包/类
public static LogcenterConfig createConfig(JSONObject jsonInput) throws LogConsumerException {
String productLine = String.valueOf(jsonInput.get("productLine"));
String appName = String.valueOf(jsonInput.get("appName"));
QueryBuilder qb = QueryBuilders.queryStringQuery("productLine:'" + productLine + "' AND appName:'" + appName + "'");
SearchResponse response = ElasticsearchClient.getClient()
.prepareSearch(Constants.METADATA_INDEX)
.setTypes(Constants.METADATA_TYPE)
.setQuery(qb)
.get();
JSONObject jsonObject = JSON.parseObject(response.toString());
JSONArray hitArray = (JSONArray) jsonObject.getJSONObject("hits").get("hits");
if (hitArray.size() == 0) {
throw new LogConsumerException("index does not exist,please check the configuration of the .logcenter index");
}
JSONObject document = (JSONObject) hitArray.get(0);
String jsonStr = document.get("_source").toString();
return JSONObject.parseObject(jsonStr, LogcenterConfig.class);
}
示例5: deleteByQuery
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的package包/类
/**
* Delete documents using a query. Check what would be deleted first with a normal search query!
* Elasticsearch once provided a native prepareDeleteByQuery method, but this was removed
* in later versions. Instead, there is a plugin which iterates over search results,
* see https://www.elastic.co/guide/en/elasticsearch/plugins/current/plugins-delete-by-query.html
* We simulate the same behaviour here without the need of that plugin.
*
* @param q
* @return delete document count
*/
public int deleteByQuery(String indexName, final QueryBuilder q) {
Map<String, String> ids = new TreeMap<>();
SearchResponse response = elasticsearchClient.prepareSearch(indexName).setSearchType(SearchType.QUERY_THEN_FETCH)
.setScroll(new TimeValue(60000)).setQuery(q).setSize(100).execute().actionGet();
while (true) {
// accumulate the ids here, don't delete them right now to prevent an interference of the delete with the
// scroll
for (SearchHit hit : response.getHits().getHits()) {
ids.put(hit.getId(), hit.getType());
}
response = elasticsearchClient.prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(600000))
.execute().actionGet();
// termination
if (response.getHits().getHits().length == 0)
break;
}
return deleteBulk(indexName, ids);
}
示例6: search
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的package包/类
@Override
public JsonNode search(JsonNode jsonQuery) {
if (jsonQuery == null) {
throw new IllegalArgumentException("JSON Query can not be null");
}
if (this.client == null) {
throw new IllegalStateException("ElasticSearch client is closed");
}
QueryBuilder query = QueryBuilders.wrapperQuery(jsonQuery.toString());
SearchResponse response = client.prepareSearch(indexNames.toArray(new String[indexNames.size()]))
.setTypes(typeNames.toArray(new String[typeNames.size()]))
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(query)
.get();
JsonNode result = null;
try {
result = mapper.readTree(response.toString());
} catch (IOException e) {
log.warn("Can not parse ES response '{}' as JSON. Exception: {}", response.toString(), e);
}
return result;
}
示例7: propertySearch
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的package包/类
@Override
public Scores propertySearch(ModifiableSearchParams searchParams, ModifiableRankParams rankParams) {
searchParams.model(BuiltInModel.PROPERTY);
if (rankParams instanceof ModifiableIndraParams) {
configureDistributionalParams(searchParams.getKbId(), (ModifiableIndraParams) rankParams);
}
QueryBuilder queryBuilder = boolQuery()
.should(nestedQuery("hyponyms",
matchQuery("hyponyms.word", searchParams.getSearchTerm()), ScoreMode.Max))
.should(nestedQuery("hypernyms",
matchQuery("hypernyms.word", searchParams.getSearchTerm()), ScoreMode.Max))
.should(nestedQuery("synonyms",
matchQuery("synonyms.word", searchParams.getSearchTerm()), ScoreMode.Max))
.minimumNumberShouldMatch(1);
Searcher searcher = core.getSearcher(searchParams.getKbId());
Scores scores = searcher.search(new ElasticQueryHolder(queryBuilder, searchParams));
return Rankers.apply(scores, rankParams, searchParams.getSearchTerm());
}
示例8: getFilters
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的package包/类
@Override
protected List<QueryBuilder> getFilters(EnumSet<ElasticsearchDocumentType> elementTypes) {
List<QueryBuilder> filters = super.getFilters(elementTypes);
List<QueryBuilder> relatedFilters = new ArrayList<>();
if (elementTypes.contains(ElasticsearchDocumentType.VERTEX)
|| elementTypes.contains(ElasticsearchDocumentType.VERTEX_EXTENDED_DATA)) {
relatedFilters.add(getVertexFilter(elementTypes));
}
if (elementTypes.contains(ElasticsearchDocumentType.EDGE)
|| elementTypes.contains(ElasticsearchDocumentType.EDGE_EXTENDED_DATA)) {
relatedFilters.add(getEdgeFilter());
}
filters.add(orFilters(relatedFilters));
return filters;
}
示例9: testGenerateQueryBuilder
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的package包/类
/**
* Tests {@link ElasticsearchQueryBuilder#generateQueryBuilder(String)} to make sure it generates the query we expect.
*/
@Test
public void testGenerateQueryBuilder() throws Exception {
final String fiqlFilter = "tenantName==taters,(containerName==delicious;tenantName==dinner)";
// Generate one of our newfangled queries
final QueryBuilder generatedBuilder = elasticsearchQueryBuilder.generateQueryBuilder(fiqlFilter);
// Use out-of-the-box approach
final FiqlParser<MetadataRecord> parser = new FiqlParser<>(MetadataRecord.class);
final ElasticsearchQueryBuilderVisitor<MetadataRecord> visitor = new ElasticsearchQueryBuilderVisitor<>();
visitor.visit(parser.parse(fiqlFilter));
final QueryBuilder builder = visitor.getQuery();
assertThat(generatedBuilder.toString(), is(builder.toString()));
}
示例10: orFilters
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的package包/类
private QueryBuilder orFilters(List<QueryBuilder> filters) {
if (filters.size() == 1) {
return filters.get(0);
} else {
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
for (QueryBuilder filter : filters) {
boolQuery.should(filter);
}
boolQuery.minimumShouldMatch(1);
return boolQuery;
}
}
示例11: getCount
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的package包/类
@Override
public Long getCount(String appid, String type) {
if (StringUtils.isBlank(appid)) {
return 0L;
}
QueryBuilder query;
if (!StringUtils.isBlank(type)) {
query = termQuery(Config._TYPE, type);
} else {
query = matchAllQuery();
}
Long count = 0L;
try {
SearchRequestBuilder crb = client().prepareSearch(getIndexName(appid)).setSize(0).setQuery(query);
count = crb.execute().actionGet().getHits().getTotalHits();
} catch (Exception e) {
Throwable cause = e.getCause();
String msg = cause != null ? cause.getMessage() : e.getMessage();
logger.warn("Could not count results in index '{}': {}", appid, msg);
}
return count;
}
示例12: phraseBoostTestCaseForClauses
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的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);
}
示例13: testStoringQueries
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的package包/类
public void testStoringQueries() throws Exception {
addQueryMapping();
QueryBuilder[] queries = new QueryBuilder[]{
termQuery("field", "value"), matchAllQuery(), matchQuery("field", "value"), matchPhraseQuery("field", "value"),
prefixQuery("field", "v"), wildcardQuery("field", "v*"), rangeQuery("number_field").gte(0).lte(9),
rangeQuery("date_field").from("2015-01-01T00:00").to("2015-01-01T00:00")
};
// note: it important that range queries never rewrite, otherwise it will cause results to be wrong.
// (it can't use shard data for rewriting purposes, because percolator queries run on MemoryIndex)
for (QueryBuilder query : queries) {
ParsedDocument doc = mapperService.documentMapper(typeName).parse("test", typeName, "1",
XContentFactory.jsonBuilder().startObject()
.field(fieldName, query)
.endObject().bytes());
BytesRef qbSource = doc.rootDoc().getFields(fieldType.queryBuilderField.name())[0].binaryValue();
assertQueryBuilder(qbSource, query);
}
}
示例14: testMultiplePercolatorFields
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的package包/类
public void testMultiplePercolatorFields() throws Exception {
String typeName = "another_type";
String percolatorMapper = XContentFactory.jsonBuilder().startObject().startObject(typeName)
.startObject("_field_names").field("enabled", false).endObject() // makes testing easier
.startObject("properties")
.startObject("query_field1").field("type", "percolator").endObject()
.startObject("query_field2").field("type", "percolator").endObject()
.endObject()
.endObject().endObject().string();
mapperService.merge(typeName, new CompressedXContent(percolatorMapper), MapperService.MergeReason.MAPPING_UPDATE, true);
QueryBuilder queryBuilder = matchQuery("field", "value");
ParsedDocument doc = mapperService.documentMapper(typeName).parse("test", typeName, "1",
jsonBuilder().startObject()
.field("query_field1", queryBuilder)
.field("query_field2", queryBuilder)
.endObject().bytes()
);
assertThat(doc.rootDoc().getFields().size(), equalTo(14)); // also includes all other meta fields
BytesRef queryBuilderAsBytes = doc.rootDoc().getField("query_field1.query_builder_field").binaryValue();
assertQueryBuilder(queryBuilderAsBytes, queryBuilder);
queryBuilderAsBytes = doc.rootDoc().getField("query_field2.query_builder_field").binaryValue();
assertQueryBuilder(queryBuilderAsBytes, queryBuilder);
}
示例15: queryToList
import org.elasticsearch.index.query.QueryBuilder; //导入依赖的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() + "");
}