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


Java SearchType类代码示例

本文整理汇总了Java中org.elasticsearch.action.search.SearchType的典型用法代码示例。如果您正苦于以下问题:Java SearchType类的具体用法?Java SearchType怎么用?Java SearchType使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


SearchType类属于org.elasticsearch.action.search包,在下文中一共展示了SearchType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: selectTermAll

import org.elasticsearch.action.search.SearchType; //导入依赖的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

示例2: calculateStats

import org.elasticsearch.action.search.SearchType; //导入依赖的package包/类
public List<DateHistogramValue> calculateStats(String sourceUrl) {
    BoolQueryBuilder filter = QueryBuilders.boolQuery()
            .must(QueryBuilders.rangeQuery("created").gte("now-1M"))
            .must(QueryBuilders.termQuery("source", sourceUrl));

    SearchResponse response = getConnection().getClient()
            .prepareSearch(getIndex())
            .setTypes(getType())
            .setSearchType(SearchType.DEFAULT)
            .setQuery(filter)
            .addAggregation(AggregationBuilders
                    .dateHistogram("urls_over_time")
                    .field("created")
                    .format("yyyy-MM-dd")
                    .dateHistogramInterval(DateHistogramInterval.DAY))
            .setSize(0)
            .setFetchSource(true)
            .setExplain(false)
            .execute()
            .actionGet();

    InternalDateHistogram hits = response.getAggregations().get("urls_over_time");
    return hits.getBuckets().stream()
            .map(b -> new DateHistogramValue(b.getKeyAsString(), b.getDocCount()))
            .collect(Collectors.toList());
}
 
开发者ID:tokenmill,项目名称:crawling-framework,代码行数:27,代码来源:EsHttpUrlOperations.java

示例3: deleteByQuery

import org.elasticsearch.action.search.SearchType; //导入依赖的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);
}
 
开发者ID:yacy,项目名称:yacy_grid_mcp,代码行数:29,代码来源:ElasticsearchClient.java

示例4: search

import org.elasticsearch.action.search.SearchType; //导入依赖的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;
}
 
开发者ID:mapr-demos,项目名称:mapr-music,代码行数:29,代码来源:ESSearchServiceBuilder.java

示例5: testScore

import org.elasticsearch.action.search.SearchType; //导入依赖的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

示例6: RandomizingClient

import org.elasticsearch.action.search.SearchType; //导入依赖的package包/类
public RandomizingClient(Client client, Random random) {
    super(client);
    // we don't use the QUERY_AND_FETCH types that break quite a lot of tests
    // given that they return `size*num_shards` hits instead of `size`
    defaultSearchType = RandomPicks.randomFrom(random, Arrays.asList(
            SearchType.DFS_QUERY_THEN_FETCH,
            SearchType.QUERY_THEN_FETCH));
    if (random.nextInt(10) == 0) {
        defaultPreference = RandomPicks.randomFrom(random, EnumSet.of(Preference.PRIMARY_FIRST, Preference.LOCAL)).type();
    } else if (random.nextInt(10) == 0) {
        String s = TestUtil.randomRealisticUnicodeString(random, 1, 10);
        defaultPreference = s.startsWith("_") ? null : s; // '_' is a reserved character
    } else {
        defaultPreference = null;
    }
    this.batchedReduceSize = 2 + random.nextInt(10);

}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:RandomizingClient.java

示例7: selectAll

import org.elasticsearch.action.search.SearchType; //导入依赖的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,项目名称:database-transform-tool,代码行数:18,代码来源:ElasticsearchTransportFactory.java

示例8: innerReadFrom

import org.elasticsearch.action.search.SearchType; //导入依赖的package包/类
protected void innerReadFrom(StreamInput in) throws IOException {
    shardId = ShardId.readShardId(in);
    searchType = SearchType.fromId(in.readByte());
    numberOfShards = in.readVInt();
    scroll = in.readOptionalWriteable(Scroll::new);
    source = in.readOptionalWriteable(SearchSourceBuilder::new);
    types = in.readStringArray();
    aliasFilter = new AliasFilter(in);
    if (in.getVersion().onOrAfter(Version.V_5_2_0_UNRELEASED)) {
        indexBoost = in.readFloat();
    } else {
        // Nodes < 5.2.0 doesn't send index boost. Read it from source.
        if (source != null) {
            Optional<SearchSourceBuilder.IndexBoost> boost = source.indexBoosts()
                .stream()
                .filter(ib -> ib.getIndex().equals(shardId.getIndexName()))
                .findFirst();
            indexBoost = boost.isPresent() ? boost.get().getBoost() : 1.0f;
        } else {
            indexBoost = 1.0f;
        }
    }
    nowInMillis = in.readVLong();
    requestCache = in.readOptionalBoolean();
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:26,代码来源:ShardSearchLocalRequest.java

示例9: toString

import org.elasticsearch.action.search.SearchType; //导入依赖的package包/类
@Override
public String toString() {
    StringBuilder result = new StringBuilder().append(shardTarget());
    if (searchType() != SearchType.DEFAULT) {
        result.append("searchType=[").append(searchType()).append("]");
    }
    if (scrollContext() != null) {
        if (scrollContext().scroll != null) {
            result.append("scroll=[").append(scrollContext().scroll.keepAlive()).append("]");
        } else {
            result.append("scroll=[null]");
        }
    }
    result.append(" query=[").append(query()).append("]");
    return result.toString();
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:SearchContext.java

示例10: deleteES

import org.elasticsearch.action.search.SearchType; //导入依赖的package包/类
private static void deleteES(Client client) {
  BulkRequestBuilder bulkRequest = client.prepareBulk();
  SearchResponse response = client.prepareSearch(index).setTypes(type)
      .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
      .setQuery(QueryBuilders.matchAllQuery())
      .setFrom(0).setSize(20).setExplain(true).execute().actionGet();
  System.out.println("length: " + response.getHits().getHits().length);
  if (response.getHits().getHits().length != 0) {
    for (SearchHit hit : response.getHits()) {
      String id = hit.getId();
      System.out.println("id: " + id);
      bulkRequest.add(client.prepareDelete(index, type, id).request());
    }
    BulkResponse bulkResponse = bulkRequest.get();
    if (bulkResponse.hasFailures()) {
      for (BulkItemResponse item : bulkResponse.getItems()) {
        System.out.println(item.getFailureMessage());
      }
    } else {
      System.out.println("delete ok");
    }
  } else {
    System.out.println("delete ok");
  }
}
 
开发者ID:MoneZhao,项目名称:elasticsearch,代码行数:26,代码来源:App.java

示例11: explain

import org.elasticsearch.action.search.SearchType; //导入依赖的package包/类
@Override
public SqlElasticSearchRequestBuilder explain() throws SqlParseException {
	this.request = client.prepareSearch();
	setIndicesAndTypes();

	setFields(select.getFields());

	setWhere(select.getWhere());
	setSorts(select.getOrderBys());
	setLimit(select.getOffset(), select.getRowCount());

	boolean usedScroll = useScrollIfNeeded(select.isOrderdSelect());
	if (!usedScroll) {
		request.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
	}
	updateRequestWithIndexAndRoutingOptions(select, request);
	updateRequestWithHighlight(select, request);

	SqlElasticSearchRequestBuilder sqlElasticRequestBuilder = new SqlElasticSearchRequestBuilder(request);

	return sqlElasticRequestBuilder;
}
 
开发者ID:mazhou,项目名称:es-sql,代码行数:23,代码来源:DefaultQueryAction.java

示例12: testNestedDiversity

import org.elasticsearch.action.search.SearchType; //导入依赖的package包/类
public void testNestedDiversity() throws Exception {
    // Test multiple samples gathered under buckets made by a parent agg
    int MAX_DOCS_PER_AUTHOR = 1;
    TermsAggregationBuilder rootTerms = terms("genres").field("genre");

    DiversifiedAggregationBuilder sampleAgg = new DiversifiedAggregationBuilder("sample").shardSize(100);
    sampleAgg.field("author").maxDocsPerValue(MAX_DOCS_PER_AUTHOR).executionHint(randomExecutionHint());
    sampleAgg.subAggregation(terms("authors").field("author"));

    rootTerms.subAggregation(sampleAgg);
    SearchResponse response = client().prepareSearch("test").setSearchType(SearchType.QUERY_THEN_FETCH)
            .addAggregation(rootTerms).execute().actionGet();
    assertSearchResponse(response);
    Terms genres = response.getAggregations().get("genres");
    Collection<Bucket> genreBuckets = genres.getBuckets();
    for (Terms.Bucket genreBucket : genreBuckets) {
        Sampler sample = genreBucket.getAggregations().get("sample");
        Terms authors = sample.getAggregations().get("authors");
        Collection<Bucket> testBuckets = authors.getBuckets();

        for (Terms.Bucket testBucket : testBuckets) {
            assertThat(testBucket.getDocCount(), lessThanOrEqualTo((long) NUM_SHARDS * MAX_DOCS_PER_AUTHOR));
        }
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:26,代码来源:DiversifiedSamplerIT.java

示例13: testSimpleSampler

import org.elasticsearch.action.search.SearchType; //导入依赖的package包/类
public void testSimpleSampler() throws Exception {
    SamplerAggregationBuilder sampleAgg = sampler("sample").shardSize(100);
    sampleAgg.subAggregation(terms("authors").field("author"));
    SearchResponse response = client().prepareSearch("test").setSearchType(SearchType.QUERY_THEN_FETCH)
            .setQuery(new TermQueryBuilder("genre", "fantasy")).setFrom(0).setSize(60).addAggregation(sampleAgg).execute().actionGet();
    assertSearchResponse(response);
    Sampler sample = response.getAggregations().get("sample");
    Terms authors = sample.getAggregations().get("authors");
    Collection<Bucket> testBuckets = authors.getBuckets();

    long maxBooksPerAuthor = 0;
    for (Terms.Bucket testBucket : testBuckets) {
        maxBooksPerAuthor = Math.max(testBucket.getDocCount(), maxBooksPerAuthor);
    }
    assertThat(maxBooksPerAuthor, equalTo(3L));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:SamplerIT.java

示例14: testUnmappedChildAggNoDiversity

import org.elasticsearch.action.search.SearchType; //导入依赖的package包/类
public void testUnmappedChildAggNoDiversity() throws Exception {
    SamplerAggregationBuilder sampleAgg = sampler("sample").shardSize(100);
    sampleAgg.subAggregation(terms("authors").field("author"));
    SearchResponse response = client().prepareSearch("idx_unmapped")
            .setSearchType(SearchType.QUERY_THEN_FETCH)
            .setQuery(new TermQueryBuilder("genre", "fantasy"))
            .setFrom(0).setSize(60)
            .addAggregation(sampleAgg)
            .execute()
            .actionGet();
    assertSearchResponse(response);
    Sampler sample = response.getAggregations().get("sample");
    assertThat(sample.getDocCount(), equalTo(0L));
    Terms authors = sample.getAggregations().get("authors");
    assertThat(authors.getBuckets().size(), equalTo(0));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:SamplerIT.java

示例15: testPartiallyUnmappedChildAggNoDiversity

import org.elasticsearch.action.search.SearchType; //导入依赖的package包/类
public void testPartiallyUnmappedChildAggNoDiversity() throws Exception {
    SamplerAggregationBuilder sampleAgg = sampler("sample").shardSize(100);
    sampleAgg.subAggregation(terms("authors").field("author"));
    SearchResponse response = client().prepareSearch("idx_unmapped", "test")
            .setSearchType(SearchType.QUERY_THEN_FETCH)
            .setQuery(new TermQueryBuilder("genre", "fantasy"))
            .setFrom(0).setSize(60).setExplain(true)
            .addAggregation(sampleAgg)
            .execute()
            .actionGet();
    assertSearchResponse(response);
    Sampler sample = response.getAggregations().get("sample");
    assertThat(sample.getDocCount(), greaterThan(0L));
    Terms authors = sample.getAggregations().get("authors");
    assertThat(authors.getBuckets().size(), greaterThan(0));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:SamplerIT.java


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