当前位置: 首页>>代码示例>>Java>>正文


Java SearchRequestBuilder类代码示例

本文整理汇总了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();
    }
}
 
开发者ID:Transwarp-DE,项目名称:Transwarp-Sample-Code,代码行数:24,代码来源:SearchES.java

示例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());
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:OldIndexBackwardsCompatibilityIT.java

示例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();
    }
}
 
开发者ID:Transwarp-DE,项目名称:Transwarp-Sample-Code,代码行数:31,代码来源:SearchES.java

示例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());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:20,代码来源:MoreExpressionTests.java

示例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);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:20,代码来源:SearchSliceIT.java

示例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);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:20,代码来源:HighlighterSearchIT.java

示例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());
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:27,代码来源:OldIndexBackwardsCompatibilityIT.java

示例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;
}
 
开发者ID:dev-share,项目名称:css-elasticsearch,代码行数:18,代码来源:ElasticsearchTransportFactory.java

示例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());
    }
}
 
开发者ID:mware-solutions,项目名称:memory-graph,代码行数:23,代码来源:Elasticsearch5SearchIndex.java

示例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()))
            );
        }
    }
}
 
开发者ID:klask-io,项目名称:klask-io,代码行数:27,代码来源:CustomSearchRepositoryImpl.java

示例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;
}
 
开发者ID:mware-solutions,项目名称:memory-graph,代码行数:21,代码来源:ElasticsearchSearchQueryBase.java

示例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);
        }
    }
}
 
开发者ID:mazhou,项目名称:es-sql,代码行数:27,代码来源:AggregationQueryAction.java

示例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());

//        }

    }
 
开发者ID:klask-io,项目名称:klask-io,代码行数:24,代码来源:CustomSearchRepositoryImpl.java

示例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);
    }
}
 
开发者ID:mazhou,项目名称:es-sql,代码行数:17,代码来源:QueryAction.java

示例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);
}
 
开发者ID:mazhou,项目名称:es-sql,代码行数:12,代码来源:HashJoinElasticExecutor.java


注:本文中的org.elasticsearch.action.search.SearchRequestBuilder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。