public void testUnsupportedQueries() { RangeQueryBuilder rangeQuery1 = new RangeQueryBuilder("field").from("2016-01-01||/D").to("2017-01-01||/D"); RangeQueryBuilder rangeQuery2 = new RangeQueryBuilder("field").from("2016-01-01||/D").to("now"); PercolatorFieldMapper.verifyQuery(rangeQuery1); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(rangeQuery2)); PercolatorFieldMapper.verifyQuery(new BoolQueryBuilder().must(rangeQuery1)); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(new BoolQueryBuilder().must(rangeQuery2))); PercolatorFieldMapper.verifyQuery(new ConstantScoreQueryBuilder((rangeQuery1))); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(new ConstantScoreQueryBuilder(rangeQuery2))); PercolatorFieldMapper.verifyQuery(new BoostingQueryBuilder(rangeQuery1, new MatchAllQueryBuilder())); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(new BoostingQueryBuilder(rangeQuery2, new MatchAllQueryBuilder()))); PercolatorFieldMapper.verifyQuery(new FunctionScoreQueryBuilder(rangeQuery1, new RandomScoreFunctionBuilder())); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(new FunctionScoreQueryBuilder(rangeQuery2, new RandomScoreFunctionBuilder()))); HasChildQueryBuilder hasChildQuery = new HasChildQueryBuilder("_type", new MatchAllQueryBuilder(), ScoreMode.None); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(hasChildQuery)); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(new BoolQueryBuilder().must(hasChildQuery))); HasParentQueryBuilder hasParentQuery = new HasParentQueryBuilder("_type", new MatchAllQueryBuilder(), false); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(hasParentQuery)); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(new BoolQueryBuilder().must(hasParentQuery))); }
/** * create random shape that is put under test */ public static QueryRescorerBuilder randomRescoreBuilder() { QueryBuilder queryBuilder = new MatchAllQueryBuilder().boost(randomFloat()) .queryName(randomAsciiOfLength(20)); org.elasticsearch.search.rescore.QueryRescorerBuilder rescorer = new org.elasticsearch.search.rescore.QueryRescorerBuilder(queryBuilder); if (randomBoolean()) { rescorer.setQueryWeight(randomFloat()); } if (randomBoolean()) { rescorer.setRescoreQueryWeight(randomFloat()); } if (randomBoolean()) { rescorer.setScoreMode(randomFrom(QueryRescoreMode.values())); } if (randomBoolean()) { rescorer.windowSize(randomIntBetween(0, 100)); } return rescorer; }
@Test public void shouldSaveTwice() { final ImmutableList.Builder<Person> builder = ImmutableList.builder(); for(int i=0; i< ElasticSearchRepository.SCROLL_SIZE * 2;i++) { builder.add(PERSON); } final List<Person> persons = builder.build(); final List<Person> saved = repository.saveAll(persons); assertEquals(persons.size(), saved.size()); final List<Person> found = repository.search(new MatchAllQueryBuilder()); assertEquals(persons.size(), found.size()); repository.deleteAll(saved); }
@Test public void should_generate_id_when_not_specified() throws IOException, ExecutionException, InterruptedException { BytesReference source = source().bytes(); IndexRequest request = Requests.indexRequest().index(THE_INDEX) .type(THE_TYPE) .source(source.toBytes()) .refresh(true); Map<String, Object> expected = SourceLookup.sourceAsMap(source); httpClient.index(request).get(); MatchAllQueryBuilder query = QueryBuilders.matchAllQuery(); SearchResponse searchResponse = new SearchRequestBuilder(transportClient).setQuery(query).setIndices(THE_INDEX).execute().actionGet(); Assertions.assertThat(searchResponse.getHits().getTotalHits()).isEqualTo(1); Assertions.assertThat(searchResponse.getHits().getHits()[0].sourceAsMap()).hasSameSizeAs(expected); compareMap(expected, searchResponse.getHits().getHits()[0].sourceAsMap()); }
public static QueryBuilder simpleQueryBuilder(String q) { if (q.equals("yacyall")) return new MatchAllQueryBuilder(); final MultiMatchQueryBuilder qb = QueryBuilders .multiMatchQuery(q) .operator(Operator.AND) .zeroTermsQuery(ZeroTermsQuery.ALL); QUERY_DEFAULT_FIELDS.forEach((mapping, boost) -> qb.field(mapping.getSolrFieldName(), boost)); return qb; }
@Override public void testMustRewrite() throws IOException { String query = "{ \"match_all\" : {}}"; QueryBuilder builder = new TemplateQueryBuilder(new Script(ScriptType.INLINE, "mockscript", query, Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()), Collections.emptyMap())); try { builder.toQuery(createShardContext()); fail(); } catch (UnsupportedOperationException ex) { assertEquals("this query must be rewritten first", ex.getMessage()); } assertEquals(new MatchAllQueryBuilder(), builder.rewrite(createShardContext())); }
public void testRewriteWithInnerName() throws IOException { final String query = "{ \"match_all\" : {\"_name\" : \"foobar\"}}"; QueryBuilder builder = new TemplateQueryBuilder(new Script(ScriptType.INLINE, "mockscript", query, Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()), Collections.emptyMap())); assertEquals(new MatchAllQueryBuilder().queryName("foobar"), builder.rewrite(createShardContext())); builder = new TemplateQueryBuilder(new Script(ScriptType.INLINE, "mockscript", query, Collections.singletonMap( Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()), Collections.emptyMap())).queryName("outer"); assertEquals(new BoolQueryBuilder().must(new MatchAllQueryBuilder().queryName("foobar")).queryName("outer"), builder.rewrite(createShardContext())); }
public void testMinScoreFunctionScoreBasic() throws IOException { index(INDEX, TYPE, jsonBuilder().startObject().field("num", 2).endObject()); refresh(); float score = randomFloat(); float minScore = randomFloat(); index(INDEX, TYPE, jsonBuilder().startObject() .field("num", 2) .field("random_score", score) // Pass the random score as a document field so that it can be extracted in the script .endObject()); refresh(); ensureYellow(); Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['random_score']", Collections.emptyMap()); SearchResponse searchResponse = client().search( searchRequest().source(searchSource().query(functionScoreQuery(scriptFunction(script)).setMinScore(minScore))) ).actionGet(); if (score < minScore) { assertThat(searchResponse.getHits().getTotalHits(), is(0L)); } else { assertThat(searchResponse.getHits().getTotalHits(), is(1L)); } searchResponse = client().search( searchRequest().source(searchSource().query(functionScoreQuery(new MatchAllQueryBuilder(), new FilterFunctionBuilder[] { new FilterFunctionBuilder(scriptFunction(script)), new FilterFunctionBuilder(scriptFunction(script)) }).scoreMode(FiltersFunctionScoreQuery.ScoreMode.AVG).setMinScore(minScore))) ).actionGet(); if (score < minScore) { assertThat(searchResponse.getHits().getTotalHits(), is(0L)); } else { assertThat(searchResponse.getHits().getTotalHits(), is(1L)); } }
public void testMinScoreFunctionScoreManyDocsAndRandomMinScore() throws IOException, ExecutionException, InterruptedException { List<IndexRequestBuilder> docs = new ArrayList<>(); int numDocs = randomIntBetween(1, 100); int scoreOffset = randomIntBetween(-2 * numDocs, 2 * numDocs); int minScore = randomIntBetween(-2 * numDocs, 2 * numDocs); for (int i = 0; i < numDocs; i++) { docs.add(client().prepareIndex(INDEX, TYPE, Integer.toString(i)).setSource("num", i + scoreOffset)); } indexRandom(true, docs); Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "return (doc['num'].value)", Collections.emptyMap()); int numMatchingDocs = numDocs + scoreOffset - minScore; if (numMatchingDocs < 0) { numMatchingDocs = 0; } if (numMatchingDocs > numDocs) { numMatchingDocs = numDocs; } SearchResponse searchResponse = client().search( searchRequest().source(searchSource().query(functionScoreQuery(scriptFunction(script)) .setMinScore(minScore)).size(numDocs))).actionGet(); assertMinScoreSearchResponses(numDocs, searchResponse, numMatchingDocs); searchResponse = client().search( searchRequest().source(searchSource().query(functionScoreQuery(new MatchAllQueryBuilder(), new FilterFunctionBuilder[] { new FilterFunctionBuilder(scriptFunction(script)), new FilterFunctionBuilder(scriptFunction(script)) }).scoreMode(FiltersFunctionScoreQuery.ScoreMode.AVG).setMinScore(minScore)).size(numDocs))).actionGet(); assertMinScoreSearchResponses(numDocs, searchResponse, numMatchingDocs); }
protected static QueryBuilder randomNestedFilter() { int id = randomIntBetween(0, 2); switch(id) { case 0: return (new MatchAllQueryBuilder()).boost(randomFloat()); case 1: return (new IdsQueryBuilder()).boost(randomFloat()); case 2: return (new TermQueryBuilder( randomAsciiOfLengthBetween(1, 10), randomDouble()).boost(randomFloat())); default: throw new IllegalStateException("Only three query builders supported for testing sort"); } }
public void testHighlightersIgnoreParentChild() { assertAcked(prepareCreate("test") .addMapping("parent-type", "searchText", "type=text,term_vector=with_positions_offsets,index_options=offsets") .addMapping("child-type", "_parent", "type=parent-type", "searchText", "type=text,term_vector=with_positions_offsets,index_options=offsets")); client().prepareIndex("test", "parent-type", "parent-id").setSource("searchText", "quick brown fox").get(); client().prepareIndex("test", "child-type", "child-id").setParent("parent-id").setSource("searchText", "quick brown fox").get(); refresh(); String[] highlightTypes = new String[] {"plain", "fvh", "postings"}; for (String highlightType : highlightTypes) { logger.info("Testing with highlight type [{}]", highlightType); SearchResponse searchResponse = client().prepareSearch("test") .setQuery(new BoolQueryBuilder() .must(new MatchQueryBuilder("searchText", "fox")) .must(new HasChildQueryBuilder("child-type", new MatchAllQueryBuilder(), ScoreMode.None)) ) .highlighter(new HighlightBuilder().field(new HighlightBuilder.Field("searchText").highlighterType(highlightType))) .get(); assertHitCount(searchResponse, 1); assertThat(searchResponse.getHits().getAt(0).getId(), equalTo("parent-id")); HighlightField highlightField = searchResponse.getHits().getAt(0).getHighlightFields().get("searchText"); assertThat(highlightField.getFragments()[0].string(), equalTo("quick brown <em>fox</em>")); searchResponse = client().prepareSearch("test") .setQuery(new BoolQueryBuilder() .must(new MatchQueryBuilder("searchText", "fox")) .must(new HasParentQueryBuilder("parent-type", new MatchAllQueryBuilder(), false)) ) .highlighter(new HighlightBuilder().field(new HighlightBuilder.Field("searchText").highlighterType(highlightType))) .get(); assertHitCount(searchResponse, 1); assertThat(searchResponse.getHits().getAt(0).getId(), equalTo("child-id")); highlightField = searchResponse.getHits().getAt(0).getHighlightFields().get("searchText"); assertThat(highlightField.getFragments()[0].string(), equalTo("quick brown <em>fox</em>")); } }
/** * Merges a top level aggregation query with an inner select * @param result * @param subQuery * @return * @throws SQLException */ private ParseResult mergeAggWithSelect(ParseResult top, ParseResult nested) throws SQLException { if(nested.getRequestScore()) throw new SQLException("Unable to request a _score on an aggregation"); int limit = top.getLimit(); List<OrderBy> sorts = top.getSorts(); boolean useCache = top.getUseCache() || nested.getUseCache(); QueryBuilder query = top.getQuery(); if(query instanceof MatchAllQueryBuilder) query = nested.getQuery(); else if(!(nested.getQuery() instanceof MatchAllQueryBuilder)) query = QueryBuilders.boolQuery().must(top.getQuery()).must(nested.getQuery()); AbstractAggregationBuilder agg = top.getAggregation(); IComparison having = top.getHaving(); Heading head = new Heading(); if(nested.getHeading().hasAllCols()){ head = top.getHeading(); }else{ for(Column col : top.getHeading().columns()){ if(col.hasCalculation()){ translateCalculation(col.getCalculation(), nested.getHeading()); head.add(new Column(col.getColumn(), col.getOp()).setAlias(col.getAlias()) .setCalculation(col.getCalculation()).setSqlType(Types.FLOAT)); }else{ Column col2 = nested.getHeading().getColumnByNameAndOp(col.getColumn(), Operation.NONE); if(col2 == null) col2 = nested.getHeading().getColumnByLabel(col.getAlias()); if(col2 == null && col.getOp() == Operation.COUNT){ head.add(col); continue; }else if(col2 == null) throw new SQLException("Unable to determine column '"+col.getLabel()+"' within nested query"); String alias = (col.getAlias() == null ? col.getColumn() : col.getAlias()); head.add(new Column(col2.getColumn(), col.getOp()).setAlias(alias).setVisible(col.isVisible()) .setSqlType(col2.getSqlType())); } } } head.buildIndex(); return new ParseResult(head, nested.getSources(), query, agg, having, sorts, limit, useCache, false); }
public KeyIterator(ElasticsearchIndex index) { this.index = index; MatchAllQueryBuilder query = QueryBuilders.matchAllQuery(); scrollResp = index.getClient().prepareSearch(index.getIndex()).setTypes(index.getType()) .addFields(new String[] {}).setSearchType(SearchType.SCAN) .setScroll(new TimeValue(ElasticsearchIndex.SCROLLTIMEOUT)).setQuery(query) .setSize(ElasticsearchIndex.SCROLLSIZE).execute().actionGet(); scrollResp = index.getClient().prepareSearchScroll(scrollResp.getScrollId()) .setScroll(new TimeValue(ElasticsearchIndex.SCROLLTIMEOUT)).execute().actionGet(); iterator = scrollResp.getHits().iterator(); }
public void download() throws IOException { String fileName = index + "_" + time + ".json"; String fullFileName = outputPath + "/" + fileName; System.out.println("Begin downloading index: " + this.index + " to " + fileName); FileOutputStream fos = new FileOutputStream(fullFileName); BufferedOutputStream bos = new BufferedOutputStream(fos); try { SearchResponse scrollResp = client.prepareSearch(index) .setSearchType(SearchType.SCAN) .setScroll(new TimeValue(SCROLL_TIMEOUT)) .setQuery(new MatchAllQueryBuilder()).setSize(SCROLL_SIZE) .execute().actionGet(); // Scroll until no hits are returned while (true) { for (SearchHit hit : scrollResp.getHits().getHits()) { bos.write(hit.source()); bos.write("\n".getBytes()); } System.out.println(Thread.currentThread().getName() + ": flushing... "); bos.flush(); scrollResp = client .prepareSearchScroll(scrollResp.getScrollId()) .setScroll(new TimeValue(SCROLL_TIMEOUT)).execute() .actionGet(); // Break condition: No hits are returned if (scrollResp.getHits().getHits().length == 0) { break; } } } finally { bos.close(); } System.out.println(Thread.currentThread().getName() + ": done"); }
public IndexDeleteByQueryResponse truncateIndex() throws InterruptedException, ExecutionException { try (Client client = getClient()) { QueryBuilder queryBuilder = new MatchAllQueryBuilder(); ListenableActionFuture<DeleteByQueryResponse> response = client.prepareDeleteByQuery(INDEX_NAME) .setTypes(DOCUMENT_TYPE).setQuery(queryBuilder).execute(); DeleteByQueryResponse deleteByQueryResponse = response.get(); IndexDeleteByQueryResponse indexResult = deleteByQueryResponse.getIndex(INDEX_NAME); return indexResult; } }
private void registerQueryParsers(List<SearchPlugin> plugins) { registerQuery(new QuerySpec<>(MatchQueryBuilder.NAME, MatchQueryBuilder::new, MatchQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(MatchPhraseQueryBuilder.NAME, MatchPhraseQueryBuilder::new, MatchPhraseQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(MatchPhrasePrefixQueryBuilder.NAME, MatchPhrasePrefixQueryBuilder::new, MatchPhrasePrefixQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(MultiMatchQueryBuilder.NAME, MultiMatchQueryBuilder::new, MultiMatchQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(NestedQueryBuilder.NAME, NestedQueryBuilder::new, NestedQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(HasChildQueryBuilder.NAME, HasChildQueryBuilder::new, HasChildQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(HasParentQueryBuilder.NAME, HasParentQueryBuilder::new, HasParentQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(DisMaxQueryBuilder.NAME, DisMaxQueryBuilder::new, DisMaxQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(IdsQueryBuilder.NAME, IdsQueryBuilder::new, IdsQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(MatchAllQueryBuilder.NAME, MatchAllQueryBuilder::new, MatchAllQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(QueryStringQueryBuilder.NAME, QueryStringQueryBuilder::new, QueryStringQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(BoostingQueryBuilder.NAME, BoostingQueryBuilder::new, BoostingQueryBuilder::fromXContent)); BooleanQuery.setMaxClauseCount(INDICES_MAX_CLAUSE_COUNT_SETTING.get(settings)); registerQuery(new QuerySpec<>(BoolQueryBuilder.NAME, BoolQueryBuilder::new, BoolQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(TermQueryBuilder.NAME, TermQueryBuilder::new, TermQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(TermsQueryBuilder.NAME, TermsQueryBuilder::new, TermsQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(FuzzyQueryBuilder.NAME, FuzzyQueryBuilder::new, FuzzyQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(RegexpQueryBuilder.NAME, RegexpQueryBuilder::new, RegexpQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(RangeQueryBuilder.NAME, RangeQueryBuilder::new, RangeQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(PrefixQueryBuilder.NAME, PrefixQueryBuilder::new, PrefixQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(WildcardQueryBuilder.NAME, WildcardQueryBuilder::new, WildcardQueryBuilder::fromXContent)); registerQuery( new QuerySpec<>(ConstantScoreQueryBuilder.NAME, ConstantScoreQueryBuilder::new, ConstantScoreQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanTermQueryBuilder.NAME, SpanTermQueryBuilder::new, SpanTermQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanNotQueryBuilder.NAME, SpanNotQueryBuilder::new, SpanNotQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanWithinQueryBuilder.NAME, SpanWithinQueryBuilder::new, SpanWithinQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanContainingQueryBuilder.NAME, SpanContainingQueryBuilder::new, SpanContainingQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(FieldMaskingSpanQueryBuilder.NAME, FieldMaskingSpanQueryBuilder::new, FieldMaskingSpanQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanFirstQueryBuilder.NAME, SpanFirstQueryBuilder::new, SpanFirstQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanNearQueryBuilder.NAME, SpanNearQueryBuilder::new, SpanNearQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanOrQueryBuilder.NAME, SpanOrQueryBuilder::new, SpanOrQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(MoreLikeThisQueryBuilder.NAME, MoreLikeThisQueryBuilder::new, MoreLikeThisQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(WrapperQueryBuilder.NAME, WrapperQueryBuilder::new, WrapperQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(CommonTermsQueryBuilder.NAME, CommonTermsQueryBuilder::new, CommonTermsQueryBuilder::fromXContent)); registerQuery( new QuerySpec<>(SpanMultiTermQueryBuilder.NAME, SpanMultiTermQueryBuilder::new, SpanMultiTermQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(FunctionScoreQueryBuilder.NAME, FunctionScoreQueryBuilder::new, FunctionScoreQueryBuilder::fromXContent)); registerQuery( new QuerySpec<>(SimpleQueryStringBuilder.NAME, SimpleQueryStringBuilder::new, SimpleQueryStringBuilder::fromXContent)); registerQuery(new QuerySpec<>(TypeQueryBuilder.NAME, TypeQueryBuilder::new, TypeQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(ScriptQueryBuilder.NAME, ScriptQueryBuilder::new, ScriptQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(GeoDistanceQueryBuilder.NAME, GeoDistanceQueryBuilder::new, GeoDistanceQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(GeoBoundingBoxQueryBuilder.NAME, GeoBoundingBoxQueryBuilder::new, GeoBoundingBoxQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(GeoPolygonQueryBuilder.NAME, GeoPolygonQueryBuilder::new, GeoPolygonQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(ExistsQueryBuilder.NAME, ExistsQueryBuilder::new, ExistsQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(MatchNoneQueryBuilder.NAME, MatchNoneQueryBuilder::new, MatchNoneQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(ParentIdQueryBuilder.NAME, ParentIdQueryBuilder::new, ParentIdQueryBuilder::fromXContent)); if (ShapesAvailability.JTS_AVAILABLE && ShapesAvailability.SPATIAL4J_AVAILABLE) { registerQuery(new QuerySpec<>(GeoShapeQueryBuilder.NAME, GeoShapeQueryBuilder::new, GeoShapeQueryBuilder::fromXContent)); } registerFromPlugin(plugins, SearchPlugin::getQueries, this::registerQuery); }
public FilterFunctionBuilder(ScoreFunctionBuilder<?> scoreFunctionBuilder) { this(new MatchAllQueryBuilder(), scoreFunctionBuilder); }
public static GeoDistanceSortBuilder randomGeoDistanceSortBuilder() { String fieldName = randomAsciiOfLengthBetween(1, 10); GeoDistanceSortBuilder result = null; int id = randomIntBetween(0, 2); switch(id) { case 0: int count = randomIntBetween(1, 10); String[] geohashes = new String[count]; for (int i = 0; i < count; i++) { geohashes[i] = RandomGeoGenerator.randomPoint(random()).geohash(); } result = new GeoDistanceSortBuilder(fieldName, geohashes); break; case 1: GeoPoint pt = RandomGeoGenerator.randomPoint(random()); result = new GeoDistanceSortBuilder(fieldName, pt.getLat(), pt.getLon()); break; case 2: result = new GeoDistanceSortBuilder(fieldName, points(new GeoPoint[0])); break; default: throw new IllegalStateException("one of three geo initialisation strategies must be used"); } if (randomBoolean()) { result.geoDistance(geoDistance(result.geoDistance())); } if (randomBoolean()) { result.unit(randomValueOtherThan(result.unit(), () -> randomFrom(DistanceUnit.values()))); } if (randomBoolean()) { result.order(randomFrom(SortOrder.values())); } if (randomBoolean()) { result.sortMode(randomValueOtherThan(SortMode.SUM, () -> randomFrom(SortMode.values()))); } if (randomBoolean()) { result.setNestedFilter(new MatchAllQueryBuilder()); } if (randomBoolean()) { result.setNestedPath( randomValueOtherThan( result.getNestedPath(), () -> randomAsciiOfLengthBetween(1, 10))); } if (randomBoolean()) { result.validation(randomValueOtherThan(result.validation(), () -> randomFrom(GeoValidationMethod.values()))); } return result; }
public void testParseSingleFunction() throws IOException { String functionScoreQuery = "{\n" + " \"function_score\":{\n" + " \"query\":{\n" + " \"term\":{\n" + " \"field1\":\"value1\"\n" + " }\n" + " },\n" + " \"gauss\": {\n" + " \"field_name\": {\n" + " \"origin\":0.5,\n" + " \"scale\":0.6\n" + " }\n" + " },\n" + " \"boost\" : 3,\n" + " \"score_mode\" : \"avg\",\n" + " \"boost_mode\" : \"replace\",\n" + " \"max_boost\" : 10\n" + " }\n" + "}"; QueryBuilder queryBuilder = parseQuery(functionScoreQuery); /* * given that we copy part of the decay functions as bytes, we test that fromXContent and toXContent both work no matter what the * initial format was */ for (int i = 0; i <= XContentType.values().length; i++) { assertThat(queryBuilder, instanceOf(FunctionScoreQueryBuilder.class)); FunctionScoreQueryBuilder functionScoreQueryBuilder = (FunctionScoreQueryBuilder) queryBuilder; assertThat(functionScoreQueryBuilder.query(), instanceOf(TermQueryBuilder.class)); TermQueryBuilder termQueryBuilder = (TermQueryBuilder) functionScoreQueryBuilder.query(); assertThat(termQueryBuilder.fieldName(), equalTo("field1")); assertThat(termQueryBuilder.value(), equalTo("value1")); assertThat(functionScoreQueryBuilder.filterFunctionBuilders().length, equalTo(1)); assertThat(functionScoreQueryBuilder.filterFunctionBuilders()[0].getFilter(), instanceOf(MatchAllQueryBuilder.class)); assertThat(functionScoreQueryBuilder.filterFunctionBuilders()[0].getScoreFunction(), instanceOf(GaussDecayFunctionBuilder.class)); GaussDecayFunctionBuilder gaussDecayFunctionBuilder = (GaussDecayFunctionBuilder) functionScoreQueryBuilder .filterFunctionBuilders()[0].getScoreFunction(); assertThat(gaussDecayFunctionBuilder.getFieldName(), equalTo("field_name")); assertThat(gaussDecayFunctionBuilder.getWeight(), nullValue()); assertThat(functionScoreQueryBuilder.boost(), equalTo(3f)); assertThat(functionScoreQueryBuilder.scoreMode(), equalTo(FiltersFunctionScoreQuery.ScoreMode.AVG)); assertThat(functionScoreQueryBuilder.boostMode(), equalTo(CombineFunction.REPLACE)); assertThat(functionScoreQueryBuilder.maxBoost(), equalTo(10f)); if (i < XContentType.values().length) { BytesReference bytes = ((AbstractQueryBuilder) queryBuilder).buildAsBytes(XContentType.values()[i]); try (XContentParser parser = createParser(XContentType.values()[i].xContent(), bytes)) { queryBuilder = parseQuery(parser); } } } }
@Override protected NamedXContentRegistry xContentRegistry() { return new NamedXContentRegistry(singletonList(new NamedXContentRegistry.Entry(QueryBuilder.class, new ParseField(MatchAllQueryBuilder.NAME), (p, c) -> MatchAllQueryBuilder.fromXContent((QueryParseContext) c)))); }
public int getDocCount(String index, String... type) { MatchAllQueryBuilder search = QueryBuilders.matchAllQuery(); String[] indexArr = new String[] { index }; return this.getDocCount(indexArr, type, search); }
public int getDocCount(String[] index, String[] type) { MatchAllQueryBuilder search = QueryBuilders.matchAllQuery(); return this.getDocCount(index, type, search); }
@Test public void shouldWithQuery() { final QueryBuilder query = new MatchAllQueryBuilder(); scroll.withQuery(query); verify(search).setQuery(query); }
@Override public QueryBuilder getDSL() { MatchAllQueryBuilder builders = matchAllQuery(); return builders; }
public int size() { MatchAllQueryBuilder query = QueryBuilders.matchAllQuery(); CountResponse response = client.prepareCount(index).setTypes(type).setQuery(query).execute().actionGet(); return MathUtil.longToInt(response.getCount()); }
public SimpleSearchQueryBuilder matchAll(){ MatchAllQueryBuilder q = matchAllQuery(); queryBuilder = q; return this; }
public MatchAllQueryBuilder matchAllBuilder(){ MatchAllQueryBuilder q = matchAllQuery(); queryBuilder = q; return q; }
/** * Creates a function_score query that executes the provided filters and functions on all documents * * @param filterFunctionBuilders the filters and functions */ public FunctionScoreQueryBuilder(FilterFunctionBuilder[] filterFunctionBuilders) { this(new MatchAllQueryBuilder(), filterFunctionBuilders); }
/** * Creates a function_score query that will execute the function provided on all documents * * @param scoreFunctionBuilder score function that is executed */ public FunctionScoreQueryBuilder(ScoreFunctionBuilder<?> scoreFunctionBuilder) { this(new MatchAllQueryBuilder(), new FilterFunctionBuilder[]{new FilterFunctionBuilder(scoreFunctionBuilder)}); }