本文整理汇总了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;
}
示例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());
}
示例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);
}
示例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;
}
示例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());
}
示例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);
}
示例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;
}
示例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();
}
示例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();
}
示例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");
}
}
示例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;
}
示例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));
}
}
}
示例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));
}
示例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));
}
示例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));
}