當前位置: 首頁>>代碼示例>>Java>>正文


Java QueryBuilders類代碼示例

本文整理匯總了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");
}
 
開發者ID:topicquests,項目名稱:backside-servlet-ks,代碼行數:19,代碼來源:ElasticQueryDSL.java

示例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);
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:21,代碼來源:RandomQueryGenerator.java

示例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();
    }
}
 
開發者ID:Transwarp-DE,項目名稱:Transwarp-Sample-Code,代碼行數:31,代碼來源:SearchES.java

示例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;
}
 
開發者ID:dev-share,項目名稱:database-transform-tool,代碼行數:26,代碼來源:ElasticsearchExtendHighRestFactory.java

示例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);
}
 
開發者ID:judasn,項目名稱:Elasticsearch-Tutorial-zh-CN,代碼行數:30,代碼來源:BaseDemo.java

示例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;
}
 
開發者ID:topicquests,項目名稱:backside-servlet-ks,代碼行數:24,代碼來源:TopicMapModel.java

示例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());
    }
}
 
開發者ID:mware-solutions,項目名稱:memory-graph,代碼行數:23,代碼來源:Elasticsearch5SearchIndex.java

示例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));
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:20,代碼來源:DfsOnlyRequest.java

示例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>."));
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:HighlighterSearchIT.java

示例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);
}
 
開發者ID:geeker-lait,項目名稱:tasfe-framework,代碼行數:20,代碼來源:LogConfigFactory.java

示例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));
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:CopyToMapperIntegrationIT.java

示例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());
        }
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:21,代碼來源:MatchedQueriesIT.java

示例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;
}
 
開發者ID:dev-share,項目名稱:css-elasticsearch,代碼行數:18,代碼來源:ElasticsearchTransportFactory.java

示例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;
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:19,代碼來源:RandomQueryGenerator.java

示例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();
}
 
開發者ID:email2liyang,項目名稱:grpc-mate,代碼行數:25,代碼來源:ProductDao.java


注:本文中的org.elasticsearch.index.query.QueryBuilders類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。