本文整理汇总了Java中org.elasticsearch.index.query.QueryBuilders类的典型用法代码示例。如果您正苦于以下问题:Java QueryBuilders类的具体用法?Java QueryBuilders怎么用?Java QueryBuilders使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
QueryBuilders类属于org.elasticsearch.index.query包,在下文中一共展示了QueryBuilders类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: test
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的package包/类
/**
* Here to establish QueryBuilder patterns
*/
void test() {
SearchSourceBuilder b;
BoolQueryBuilder qb = QueryBuilders.boolQuery();
QueryBuilder qbmm = QueryBuilders.multiMatchQuery("name", "fieldNames");
QueryBuilder qbm = QueryBuilders.matchQuery("name", "text");
QueryBuilder qbmp = QueryBuilders.matchPhraseQuery("name", "text");
QueryBuilder qb1 = QueryBuilders.termQuery(ITQCoreOntology.TUPLE_SUBJECT_PROPERTY, "");
QueryBuilder qb2 = QueryBuilders.termQuery(ITQCoreOntology.TUPLE_OBJECT_PROPERTY, "");
QueryBuilder qb3 = QueryBuilders.termQuery(ITQCoreOntology.INSTANCE_OF_PROPERTY_TYPE, "");
qb.must(qb3);
qb.should(qb1);
qb.should(qb2);
QueryBuilder partial = QueryBuilders.regexpQuery("name", "regexp");
QueryBuilder wildcard = QueryBuilders.wildcardQuery("name", "query");
}
示例2: randomTerminalQuery
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的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);
}
}
示例3: wildcardQuery
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的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: selectTermAll
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的package包/类
public String selectTermAll(String indexs,String types,String field,String value){
try {
if(StringUtil.isEmpty(indexs))indexs="_all";
if(xclient==null){
init();
}
SearchSourceBuilder search = new SearchSourceBuilder();
if(!StringUtil.isEmpty(field)&&!StringUtil.isEmpty(value)&&!(field.matches(regex)||field.matches(value))){
search.query(QueryBuilders.termQuery(field, value));
}
search.aggregation(AggregationBuilders.terms("data").field(field+".keyword"));
search.explain(false);
SearchRequest request = new SearchRequest();
request.searchType(SearchType.DFS_QUERY_THEN_FETCH);
request.source(search);
request.indices(indexs.split(","));
request.types(types.split(","));
SearchResponse response = xclient.search(request);
return response.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
示例5: queryByScroll
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的package包/类
/**
* Scroll 获取多个对象
*
* @param transportClient
* @throws IOException
*/
private static void queryByScroll(TransportClient transportClient) throws IOException {
//setSize 是设置每批查询多少条数据
SearchResponse searchResponse = transportClient.prepareSearch("product_index").setTypes("product")
.setQuery(QueryBuilders.termQuery("product_name", "飞利浦"))
.setScroll(new TimeValue(60000))
.setSize(3)
.get();
int count = 0;
do {
for (SearchHit searchHit : searchResponse.getHits().getHits()) {
//打印查询结果,或者做其他处理
logger.info("count=" + ++count);
logger.info(searchHit.getSourceAsString());
}
searchResponse = transportClient.prepareSearchScroll(searchResponse.getScrollId()).setScroll(new TimeValue(60000))
.execute()
.actionGet();
} while (searchResponse.getHits().getHits().length != 0);
}
示例6: listTopicsByURL
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的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;
}
示例7: deleteExtendedDataForElement
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的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());
}
}
示例8: DfsOnlyRequest
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的package包/类
public DfsOnlyRequest(Fields termVectorsFields, String[] indices, String[] types, Set<String> selectedFields) throws IOException {
super(indices);
// build a search request with a query of all the terms
final BoolQueryBuilder boolBuilder = boolQuery();
for (String fieldName : termVectorsFields) {
if ((selectedFields != null) && (!selectedFields.contains(fieldName))) {
continue;
}
Terms terms = termVectorsFields.terms(fieldName);
TermsEnum iterator = terms.iterator();
while (iterator.next() != null) {
String text = iterator.term().utf8ToString();
boolBuilder.should(QueryBuilders.termQuery(fieldName, text));
}
}
// wrap a search request object
this.searchRequest = new SearchRequest(indices).types(types).source(new SearchSourceBuilder().query(boolBuilder));
}
示例9: testPostingsHighlighterMultipleFields
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的package包/类
public void testPostingsHighlighterMultipleFields() throws Exception {
assertAcked(prepareCreate("test").addMapping("type1", type1PostingsffsetsMapping()).get());
ensureGreen();
index("test", "type1", "1",
"field1", "The <b>quick<b> brown fox. Second sentence.",
"field2", "The <b>slow<b> brown fox. Second sentence.");
refresh();
for (String type : UNIFIED_AND_NULL) {
SearchResponse response = client().prepareSearch("test")
.setQuery(QueryBuilders.matchQuery("field1", "fox"))
.highlighter(
new HighlightBuilder().field(new Field("field1").preTags("<1>").postTags("</1>")
.requireFieldMatch(true).highlighterType(type)))
.get();
assertHighlight(response, 0, "field1", 0, 1, equalTo("The <b>quick<b> brown <1>fox</1>."));
}
}
示例10: createConfig
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的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);
}
示例11: testDynamicObjectCopyTo
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的package包/类
public void testDynamicObjectCopyTo() throws Exception {
String mapping = jsonBuilder().startObject().startObject("doc").startObject("properties")
.startObject("foo")
.field("type", "text")
.field("copy_to", "root.top.child")
.endObject()
.endObject().endObject().endObject().string();
assertAcked(
client().admin().indices().prepareCreate("test-idx")
.addMapping("doc", mapping, XContentType.JSON)
);
client().prepareIndex("test-idx", "doc", "1")
.setSource("foo", "bar")
.get();
client().admin().indices().prepareRefresh("test-idx").execute().actionGet();
SearchResponse response = client().prepareSearch("test-idx")
.setQuery(QueryBuilders.termQuery("root.top.child", "bar")).get();
assertThat(response.getHits().getTotalHits(), equalTo(1L));
}
示例12: testRegExpQuerySupportsName
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的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());
}
}
}
示例13: selectAll
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的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;
}
示例14: randomDisMaxQuery
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的package包/类
private static QueryBuilder randomDisMaxQuery(List<String> stringFields, List<String> numericFields, int numDocs, int depth) {
QueryBuilder q = QueryBuilders.disMaxQuery();
int numClauses = randomIntBetween(1, 10);
for (int i = 0; i < numClauses; i++) {
((DisMaxQueryBuilder)q).add(randomQueryBuilder(stringFields, numericFields, numDocs, depth - 1));
}
if (randomBoolean()) {
((DisMaxQueryBuilder)q).boost(randomFloat());
}
if (randomBoolean()) {
((DisMaxQueryBuilder)q).tieBreaker(randomFloat());
}
return q;
}
示例15: searchProducts
import org.elasticsearch.index.query.QueryBuilders; //导入依赖的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();
}