diff --git a/docs/reference/aggregations/bucket/geohashgrid-aggregation.asciidoc b/docs/reference/aggregations/bucket/geohashgrid-aggregation.asciidoc index e90e1c95deb..b550b240b75 100644 --- a/docs/reference/aggregations/bucket/geohashgrid-aggregation.asciidoc +++ b/docs/reference/aggregations/bucket/geohashgrid-aggregation.asciidoc @@ -57,7 +57,7 @@ Response: ==== High-precision requests -When requesting detailed buckets (typically for displaying a "zoomed in" map) a filter like <> should be applied to narrow the subject area otherwise potentially millions of buckets will be created and returned. +When requesting detailed buckets (typically for displaying a "zoomed in" map) a filter like <> should be applied to narrow the subject area otherwise potentially millions of buckets will be created and returned. [source,js] -------------------------------------------------- diff --git a/docs/reference/api-conventions.asciidoc b/docs/reference/api-conventions.asciidoc index bbf78eb1521..fc8b60a91af 100644 --- a/docs/reference/api-conventions.asciidoc +++ b/docs/reference/api-conventions.asciidoc @@ -157,7 +157,7 @@ can be specified as a whole number representing time in milliseconds, or as a ti === Distance Units Wherever distances need to be specified, such as the `distance` parameter in -the <>), the default unit if none is specified is +the <>), the default unit if none is specified is the meter. Distances can be specified in other units, such as `"1km"` or `"2mi"` (2 miles). @@ -174,7 +174,7 @@ Centimeter:: `cm` or `centimeters` Millimeter:: `mm` or `millimeters` Nautical mile:: `NM`, `nmi` or `nauticalmiles` -The `precision` parameter in the <> accepts +The `precision` parameter in the <> accepts distances with the above units, but if no unit is specified, then the precision is interpreted as the length of the geohash. diff --git a/docs/reference/getting-started.asciidoc b/docs/reference/getting-started.asciidoc index 358c5f09ef8..f21ed1162e1 100755 --- a/docs/reference/getting-started.asciidoc +++ b/docs/reference/getting-started.asciidoc @@ -865,12 +865,9 @@ curl -XPOST 'localhost:9200/bank/_search?pretty' -d ' In the previous section, we skipped over a little detail called the document score (`_score` field in the search results). The score is a numeric value that is a relative measure of how well the document matches the search query that we specified. The higher the score, the more relevant the document is, the lower the score, the less relevant the document is. -All queries in Elasticsearch trigger computation of the relevance scores. In cases where we do not need the relevance scores, Elasticsearch provides another query capability in the form of <. Filters are similar in concept to queries except that they are optimized for much faster execution speeds for two primary reasons: +But queries do not always to produce scores, in particular when they are only used for "filtering" the document set. Elasticsearch detects these situations and automatically optimizes query execution in order not to compute useless scores. -* Filters do not score so they are faster to execute than queries -* Filters can be http://www.elastic.co/blog/all-about-elasticsearch-filter-bitsets/[cached in memory] allowing repeated search executions to be significantly faster than queries - -To understand filters, let's first introduce the <>, which allows you to combine a query (like `match_all`, `match`, `bool`, etc.) together with a filter. As an example, let's introduce the <>, which allows us to filter documents by a range of values. This is generally used for numeric or date filtering. +To understand filters, let's first introduce the <>, which allows you to combine a query (like `match_all`, `match`, `bool`, etc.) together with another query which is only used for filtering. As an example, let's introduce the <>, which allows us to filter documents by a range of values. This is generally used for numeric or date filtering. This example uses a filtered query to return all accounts with balances between 20000 and 30000, inclusive. In other words, we want to find accounts with a balance that is greater than or equal to 20000 and less than or equal to 30000. @@ -894,11 +891,9 @@ curl -XPOST 'localhost:9200/bank/_search?pretty' -d ' }' -------------------------------------------------- -Dissecting the above, the filtered query contains a `match_all` query (the query part) and a `range` filter (the filter part). We can substitute any other query into the query part as well as any other filter into the filter part. In the above case, the range filter makes perfect sense since documents falling into the range all match "equally", i.e., no document is more relevant than another. +Dissecting the above, the filtered query contains a `match_all` query (the query part) and a `range` query (the filter part). We can substitute any other queries into the query and the filter parts. In the above case, the range query makes perfect sense since documents falling into the range all match "equally", i.e., no document is more relevant than another. -In general, the easiest way to decide whether you want a filter or a query is to ask yourself if you care about the relevance score or not. If relevance is not important, use filters, otherwise, use queries. If you come from a SQL background, queries and filters are similar in concept to the `SELECT WHERE` clause, although more so for filters than queries. - -In addition to the `match_all`, `match`, `bool`, `filtered`, and `range` queries, there are a lot of other query/filter types that are available and we won't go into them here. Since we already have a basic understanding of how they work, it shouldn't be too difficult to apply this knowledge in learning and experimenting with the other query/filter types. +In addition to the `match_all`, `match`, `bool`, `filtered`, and `range` queries, there are a lot of other query types that are available and we won't go into them here. Since we already have a basic understanding of how they work, it shouldn't be too difficult to apply this knowledge in learning and experimenting with the other query types. === Executing Aggregations diff --git a/docs/reference/mapping/types/geo-point-type.asciidoc b/docs/reference/mapping/types/geo-point-type.asciidoc index 2d3f3ad6dd2..35f3600468e 100644 --- a/docs/reference/mapping/types/geo-point-type.asciidoc +++ b/docs/reference/mapping/types/geo-point-type.asciidoc @@ -52,7 +52,7 @@ length (eg `12`, the default) or to a distance (eg `1km`). More usefully, set the `geohash_prefix` option to `true` to not only index the geohash value, but all the enclosing cells as well. For instance, a geohash of `u30` will be indexed as `[u,u3,u30]`. This option can be used -by the <> to find geopoints within a +by the <> to find geopoints within a particular cell very efficiently. [float] diff --git a/docs/reference/mapping/types/geo-shape-type.asciidoc b/docs/reference/mapping/types/geo-shape-type.asciidoc index 914bbbd3b13..0e2074365b3 100644 --- a/docs/reference/mapping/types/geo-shape-type.asciidoc +++ b/docs/reference/mapping/types/geo-shape-type.asciidoc @@ -7,9 +7,7 @@ used when either the data being indexed or the queries being executed contain shapes other than just points. You can query documents using this type using -<> -or <>. +<>. [[geo-shape-mapping-options]] [float] diff --git a/docs/reference/mapping/types/nested-type.asciidoc b/docs/reference/mapping/types/nested-type.asciidoc index 21b1110faf3..d507f535af8 100644 --- a/docs/reference/mapping/types/nested-type.asciidoc +++ b/docs/reference/mapping/types/nested-type.asciidoc @@ -64,8 +64,7 @@ By keeping each nested object separate, the association between the smith` would *not* match this document. Searching on nested docs can be done using either the -<> or -<>. +<>. ==== Mapping diff --git a/docs/reference/migration/migrate_1_4.asciidoc b/docs/reference/migration/migrate_1_4.asciidoc index 7aad5d67e23..03a4c1fe741 100644 --- a/docs/reference/migration/migrate_1_4.asciidoc +++ b/docs/reference/migration/migrate_1_4.asciidoc @@ -20,7 +20,7 @@ two ways to make sure that a field mapping exist: [float] === Aliases -<> can include <> which +<> can include <> which are automatically applied to any search performed via the alias. <> created with version `1.4.0` or later can only refer to field names which exist in the mappings of the index (or indices) diff --git a/docs/reference/migration/migrate_2_0.asciidoc b/docs/reference/migration/migrate_2_0.asciidoc index 5f02d4a953b..2bdd5fe90d3 100644 --- a/docs/reference/migration/migrate_2_0.asciidoc +++ b/docs/reference/migration/migrate_2_0.asciidoc @@ -108,7 +108,11 @@ in addition to the actual HTTP status code. We removed `status` field in json re === Java API -Some query builders have been removed or renamed: +`org.elasticsearch.index.queries.FilterBuilders` has been removed as part of the merge of +queries and filters. These filters are now available in `QueryBuilders` with the same name. +All methods that used to accept a `FilterBuilder` now accept a `QueryBuilder` instead. + +In addition some query builders have been removed or renamed: * `commonTerms(...)` renamed with `commonTermsQuery(...)` * `queryString(...)` renamed with `queryStringQuery(...)` @@ -436,6 +440,14 @@ ignored. Instead filters are always used as their own cache key and elasticsearc makes decisions by itself about whether it should cache filters based on how often they are used. +==== Query/filter merge + +Elasticsearch no longer makes a difference between queries and filters in the +DSL; it detects when scores are not needed and automatically optimizes the +query to not compute scores and optionally caches the result. + +As a consequence the `query` filter serves no purpose anymore and is deprecated. + === Snapshot and Restore The obsolete parameters `expand_wildcards_open` and `expand_wildcards_close` are no longer diff --git a/docs/reference/query-dsl.asciidoc b/docs/reference/query-dsl.asciidoc index cd57891ca36..3f2869e5981 100644 --- a/docs/reference/query-dsl.asciidoc +++ b/docs/reference/query-dsl.asciidoc @@ -8,35 +8,27 @@ queries. In general, there are basic queries such as <> or <>. There are also compound queries like the -<> query. Queries can -also have filters associated with them such as the +<> query. + +While queries have scoring capabilities, in some contexts they will +only be used to filter the result set, such as in the <> or <> -queries, with specific filter queries. +queries. -Think of the Query DSL as an AST of queries. Certain queries can contain -other queries (like the -<> query), others can -contain filters (like the -<>), -and some can contain both a query and a filter (like the -<>). Each of -those can contain *any* query of the list of queries or *any* filter -from the list of filters, resulting in the ability to build quite +Think of the Query DSL as an AST of queries. +Some queries can be used by themselves like the +<> query but other queries can contain +queries (like the <> query), and each +of these composite queries can contain *any* query of the list of +queries, resulting in the ability to build quite complex (and interesting) queries. -Both queries and filters can be used in different APIs. For example, +Queries can be used in different APIs. For example, within a <>, or as an <>. -This section explains the components (queries and filters) that can form the -AST one can use. - -Filters are very handy since they perform an order of magnitude better -than plain queries since no scoring is performed and they are -automatically cached. +This section explains the queries that can form the AST one can use. -- -include::query-dsl/queries.asciidoc[] - -include::query-dsl/filters.asciidoc[] +include::query-dsl/index.asciidoc[] diff --git a/docs/reference/query-dsl/filters/and-filter.asciidoc b/docs/reference/query-dsl/and-query.asciidoc similarity index 74% rename from docs/reference/query-dsl/filters/and-filter.asciidoc rename to docs/reference/query-dsl/and-query.asciidoc index 9484d4bf999..15a52e57b16 100644 --- a/docs/reference/query-dsl/filters/and-filter.asciidoc +++ b/docs/reference/query-dsl/and-query.asciidoc @@ -1,10 +1,10 @@ -[[query-dsl-and-filter]] -=== And Filter +[[query-dsl-and-query]] +== And Query -deprecated[2.0.0, Use the `bool` filter instead] +deprecated[2.0.0, Use the `bool` query instead] -A filter that matches documents using the `AND` boolean operator on other -filters. Can be placed within queries that accept a filter. +A query that matches documents using the `AND` boolean operator on other +queries. [source,js] -------------------------------------------------- diff --git a/docs/reference/query-dsl/queries/bool-query.asciidoc b/docs/reference/query-dsl/bool-query.asciidoc similarity index 92% rename from docs/reference/query-dsl/queries/bool-query.asciidoc rename to docs/reference/query-dsl/bool-query.asciidoc index b496796dba2..e6d90cce766 100644 --- a/docs/reference/query-dsl/queries/bool-query.asciidoc +++ b/docs/reference/query-dsl/bool-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-bool-query]] -=== Bool Query +== Bool Query A query that matches documents matching boolean combinations of other queries. The bool query maps to Lucene `BooleanQuery`. It is built using @@ -22,6 +22,9 @@ parameter. documents. |======================================================================= +IMPORTANT: If this query is used in a filter context and it has `should` +clauses then at least one `should` clause is required to match. + The bool query also supports `disable_coord` parameter (defaults to `false`). Basically the coord similarity computes a score factor based on the fraction of all query terms that a document contains. See Lucene diff --git a/docs/reference/query-dsl/queries/boosting-query.asciidoc b/docs/reference/query-dsl/boosting-query.asciidoc similarity index 97% rename from docs/reference/query-dsl/queries/boosting-query.asciidoc rename to docs/reference/query-dsl/boosting-query.asciidoc index 969b3bbedfe..752fc2b9f64 100644 --- a/docs/reference/query-dsl/queries/boosting-query.asciidoc +++ b/docs/reference/query-dsl/boosting-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-boosting-query]] -=== Boosting Query +== Boosting Query The `boosting` query can be used to effectively demote results that match a given query. Unlike the "NOT" clause in bool query, this still diff --git a/docs/reference/query-dsl/queries/common-terms-query.asciidoc b/docs/reference/query-dsl/common-terms-query.asciidoc similarity index 99% rename from docs/reference/query-dsl/queries/common-terms-query.asciidoc rename to docs/reference/query-dsl/common-terms-query.asciidoc index b9aee04e401..1c5fa7cc1f6 100644 --- a/docs/reference/query-dsl/queries/common-terms-query.asciidoc +++ b/docs/reference/query-dsl/common-terms-query.asciidoc @@ -1,12 +1,12 @@ [[query-dsl-common-terms-query]] -=== Common Terms Query +== Common Terms Query The `common` terms query is a modern alternative to stopwords which improves the precision and recall of search results (by taking stopwords into account), without sacrificing performance. [float] -==== The problem +=== The problem Every term in a query has a cost. A search for `"The brown fox"` requires three term queries, one for each of `"the"`, `"brown"` and @@ -25,7 +25,7 @@ and `"not happy"`) and we lose recall (eg text like `"The The"` or `"To be or not to be"` would simply not exist in the index). [float] -==== The solution +=== The solution The `common` terms query divides the query terms into two groups: more important (ie _low frequency_ terms) and less important (ie _high @@ -63,7 +63,7 @@ site, common terms like `"clip"` or `"video"` will automatically behave as stopwords without the need to maintain a manual list. [float] -==== Examples +=== Examples In this example, words that have a document frequency greater than 0.1% (eg `"this"` and `"is"`) will be treated as _common terms_. diff --git a/docs/reference/query-dsl/constant-score-query.asciidoc b/docs/reference/query-dsl/constant-score-query.asciidoc new file mode 100644 index 00000000000..e31b7b801a5 --- /dev/null +++ b/docs/reference/query-dsl/constant-score-query.asciidoc @@ -0,0 +1,18 @@ +[[query-dsl-constant-score-query]] +== Constant Score Query + +A query that wraps another query and simply returns a +constant score equal to the query boost for every document in the +filter. Maps to Lucene `ConstantScoreQuery`. + +[source,js] +-------------------------------------------------- +{ + "constant_score" : { + "filter" : { + "term" : { "user" : "kimchy"} + }, + "boost" : 1.2 + } +} +-------------------------------------------------- diff --git a/docs/reference/query-dsl/queries/dis-max-query.asciidoc b/docs/reference/query-dsl/dis-max-query.asciidoc similarity index 98% rename from docs/reference/query-dsl/queries/dis-max-query.asciidoc rename to docs/reference/query-dsl/dis-max-query.asciidoc index 2938c8db8ea..ae8445ca5dd 100644 --- a/docs/reference/query-dsl/queries/dis-max-query.asciidoc +++ b/docs/reference/query-dsl/dis-max-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-dis-max-query]] -=== Dis Max Query +== Dis Max Query A query that generates the union of documents produced by its subqueries, and that scores each document with the maximum score for diff --git a/docs/reference/query-dsl/filters/exists-filter.asciidoc b/docs/reference/query-dsl/exists-query.asciidoc similarity index 92% rename from docs/reference/query-dsl/filters/exists-filter.asciidoc rename to docs/reference/query-dsl/exists-query.asciidoc index a1eb0535f1e..02460da7b65 100644 --- a/docs/reference/query-dsl/filters/exists-filter.asciidoc +++ b/docs/reference/query-dsl/exists-query.asciidoc @@ -1,5 +1,5 @@ -[[query-dsl-exists-filter]] -=== Exists Filter +[[query-dsl-exists-query]] +== Exists Query Returns documents that have at least one non-`null` value in the original field: @@ -14,7 +14,7 @@ Returns documents that have at least one non-`null` value in the original field: } -------------------------------------------------- -For instance, these documents would all match the above filter: +For instance, these documents would all match the above query: [source,js] -------------------------------------------------- @@ -28,7 +28,7 @@ For instance, these documents would all match the above filter: <2> Even though the `standard` analyzer would emit zero tokens, the original field is non-`null`. <3> At least one non-`null` value is required. -These documents would *not* match the above filter: +These documents would *not* match the above query: [source,js] -------------------------------------------------- diff --git a/docs/reference/query-dsl/queries/filtered-query.asciidoc b/docs/reference/query-dsl/filtered-query.asciidoc similarity index 85% rename from docs/reference/query-dsl/queries/filtered-query.asciidoc rename to docs/reference/query-dsl/filtered-query.asciidoc index 91ff294c2d9..655cfa804c4 100644 --- a/docs/reference/query-dsl/queries/filtered-query.asciidoc +++ b/docs/reference/query-dsl/filtered-query.asciidoc @@ -1,14 +1,9 @@ [[query-dsl-filtered-query]] -=== Filtered Query +== Filtered Query -The `filtered` query is used to combine another query with any -<>. Filters are usually faster than queries because: - -* they don't have to calculate the relevance `_score` for each document -- - the answer is just a boolean ``Yes, the document matches the filter'' or - ``No, the document does not match the filter''. -* the results from most filters can be cached in memory, making subsequent - executions faster. +The `filtered` query is used to combine a query which will be used for +scoring with another query which will only be used for filtering the result +set. TIP: Exclude as many document as you can with a filter, then query just the documents that remain. @@ -50,7 +45,7 @@ curl -XGET localhost:9200/_search -d ' <1> The `filtered` query is passed as the value of the `query` parameter in the search request. -==== Filtering without a query +=== Filtering without a query If a `query` is not specified, it defaults to the <>. This means that the @@ -77,7 +72,7 @@ curl -XGET localhost:9200/_search -d ' ==== Multiple filters Multiple filters can be applied by wrapping them in a -<>, for example: +<>, for example: [source,js] -------------------------------------------------- @@ -98,9 +93,6 @@ Multiple filters can be applied by wrapping them in a } -------------------------------------------------- -Similarly, multiple queries can be combined with a -<>. - ==== Filter strategy You can control how the filter and query are executed with the `strategy` diff --git a/docs/reference/query-dsl/filters.asciidoc b/docs/reference/query-dsl/filters.asciidoc deleted file mode 100644 index 59a4a06caec..00000000000 --- a/docs/reference/query-dsl/filters.asciidoc +++ /dev/null @@ -1,77 +0,0 @@ -[[query-dsl-filters]] -== Filters - -As a general rule, filters should be used instead of queries: - -* for binary yes/no searches -* for queries on exact values - -[float] -[[caching]] -=== Filters and Caching - -Filters can be a great candidate for caching. Caching the document set that -a filter matches does not require much memory and can help improve -execution speed of queries. - -Elasticsearch decides to cache filters based on how often they are used. For -this reason you might occasionally see better performance by splitting -complex filters into a static part that Elasticsearch will cache and a dynamic -part which is least costly than the original filter. - -include::filters/and-filter.asciidoc[] - -include::filters/bool-filter.asciidoc[] - -include::filters/exists-filter.asciidoc[] - -include::filters/geo-bounding-box-filter.asciidoc[] - -include::filters/geo-distance-filter.asciidoc[] - -include::filters/geo-distance-range-filter.asciidoc[] - -include::filters/geo-polygon-filter.asciidoc[] - -include::filters/geo-shape-filter.asciidoc[] - -include::filters/geohash-cell-filter.asciidoc[] - -include::filters/has-child-filter.asciidoc[] - -include::filters/has-parent-filter.asciidoc[] - -include::filters/ids-filter.asciidoc[] - -include::filters/indices-filter.asciidoc[] - -include::filters/limit-filter.asciidoc[] - -include::filters/match-all-filter.asciidoc[] - -include::filters/missing-filter.asciidoc[] - -include::filters/nested-filter.asciidoc[] - -include::filters/not-filter.asciidoc[] - -include::filters/or-filter.asciidoc[] - -include::filters/prefix-filter.asciidoc[] - -include::filters/query-filter.asciidoc[] - -include::filters/range-filter.asciidoc[] - -include::filters/regexp-filter.asciidoc[] - -include::filters/script-filter.asciidoc[] - -include::filters/term-filter.asciidoc[] - -include::filters/terms-filter.asciidoc[] - -include::filters/type-filter.asciidoc[] - - - diff --git a/docs/reference/query-dsl/filters/bool-filter.asciidoc b/docs/reference/query-dsl/filters/bool-filter.asciidoc deleted file mode 100644 index 5f6b86021ab..00000000000 --- a/docs/reference/query-dsl/filters/bool-filter.asciidoc +++ /dev/null @@ -1,43 +0,0 @@ -[[query-dsl-bool-filter]] -=== Bool Filter - -A filter that matches documents matching boolean combinations of other -queries. Similar in concept to -<>, except -that the clauses are other filters. Can be placed within queries that -accept a filter. - -[source,js] --------------------------------------------------- -{ - "filtered" : { - "query" : { - "queryString" : { - "default_field" : "message", - "query" : "elasticsearch" - } - }, - "filter" : { - "bool" : { - "must" : { - "term" : { "tag" : "wow" } - }, - "must_not" : { - "range" : { - "age" : { "gte" : 10, "lt" : 20 } - } - }, - "should" : [ - { - "term" : { "tag" : "sometag" } - }, - { - "term" : { "tag" : "sometagtag" } - } - ] - } - } - } -} --------------------------------------------------- - diff --git a/docs/reference/query-dsl/filters/has-child-filter.asciidoc b/docs/reference/query-dsl/filters/has-child-filter.asciidoc deleted file mode 100644 index 8f3be2a57ff..00000000000 --- a/docs/reference/query-dsl/filters/has-child-filter.asciidoc +++ /dev/null @@ -1,90 +0,0 @@ -[[query-dsl-has-child-filter]] -=== Has Child Filter - -The `has_child` filter accepts a query and the child type to run -against, and results in parent documents that have child docs matching -the query. Here is an example: - -[source,js] --------------------------------------------------- -{ - "has_child" : { - "type" : "blog_tag", - "query" : { - "term" : { - "tag" : "something" - } - } - } -} --------------------------------------------------- - -The `type` is the child type to query against. The parent type to return -is automatically detected based on the mappings. - -The way that the filter is implemented is by first running the child -query, doing the matching up to the parent doc for each document -matched. - -The `has_child` filter also accepts a filter instead of a query: - -[source,js] --------------------------------------------------- -{ - "has_child" : { - "type" : "comment", - "filter" : { - "term" : { - "user" : "john" - } - } - } -} --------------------------------------------------- - -[float] -==== Min/Max Children - -The `has_child` filter allows you to specify that a minimum and/or maximum -number of children are required to match for the parent doc to be considered -a match: - -[source,js] --------------------------------------------------- -{ - "has_child" : { - "type" : "comment", - "min_children": 2, <1> - "max_children": 10, <1> - "filter" : { - "term" : { - "user" : "john" - } - } - } -} --------------------------------------------------- -<1> Both `min_children` and `max_children` are optional. - -The execution speed of the `has_child` filter is equivalent -to that of the `has_child` query when `min_children` or `max_children` -is specified. - -[float] -==== Memory Considerations - -In order to support parent-child joins, all of the (string) parent IDs -must be resident in memory (in the <>. -Additionally, every child document is mapped to its parent using a long -value (approximately). It is advisable to keep the string parent ID short -in order to reduce memory usage. - -You can check how much memory is being used by the ID cache using the -<> or <> -APIS, eg: - -[source,js] --------------------------------------------------- -curl -XGET "http://localhost:9200/_stats/id_cache?pretty&human" --------------------------------------------------- - diff --git a/docs/reference/query-dsl/filters/has-parent-filter.asciidoc b/docs/reference/query-dsl/filters/has-parent-filter.asciidoc deleted file mode 100644 index 1f43c47d41d..00000000000 --- a/docs/reference/query-dsl/filters/has-parent-filter.asciidoc +++ /dev/null @@ -1,65 +0,0 @@ -[[query-dsl-has-parent-filter]] -=== Has Parent Filter - -The `has_parent` filter accepts a query and a parent type. The query is -executed in the parent document space, which is specified by the parent -type. This filter returns child documents which associated parents have -matched. For the rest `has_parent` filter has the same options and works -in the same manner as the `has_child` filter. - -[float] -==== Filter example - -[source,js] --------------------------------------------------- -{ - "has_parent" : { - "parent_type" : "blog", - "query" : { - "term" : { - "tag" : "something" - } - } - } -} --------------------------------------------------- - -The `parent_type` field name can also be abbreviated to `type`. - -The way that the filter is implemented is by first running the parent -query, doing the matching up to the child doc for each document matched. - -The `has_parent` filter also accepts a filter instead of a query: - -[source,js] --------------------------------------------------- -{ - "has_parent" : { - "type" : "blog", - "filter" : { - "term" : { - "text" : "bonsai three" - } - } - } -} --------------------------------------------------- - -[float] -==== Memory Considerations - -In order to support parent-child joins, all of the (string) parent IDs -must be resident in memory (in the <>. -Additionally, every child document is mapped to its parent using a long -value (approximately). It is advisable to keep the string parent ID short -in order to reduce memory usage. - -You can check how much memory is being used by the ID cache using the -<> or <> -APIS, eg: - -[source,js] --------------------------------------------------- -curl -XGET "http://localhost:9200/_stats/id_cache?pretty&human" --------------------------------------------------- - diff --git a/docs/reference/query-dsl/filters/ids-filter.asciidoc b/docs/reference/query-dsl/filters/ids-filter.asciidoc deleted file mode 100644 index 303fffb9236..00000000000 --- a/docs/reference/query-dsl/filters/ids-filter.asciidoc +++ /dev/null @@ -1,20 +0,0 @@ -[[query-dsl-ids-filter]] -=== Ids Filter - -Filters documents that only have the provided ids. Note, this filter -does not require the <> -field to be indexed since it works using the -<> field. - -[source,js] --------------------------------------------------- -{ - "ids" : { - "type" : "my_type", - "values" : ["1", "4", "100"] - } -} --------------------------------------------------- - -The `type` is optional and can be omitted, and can also accept an array -of values. diff --git a/docs/reference/query-dsl/filters/indices-filter.asciidoc b/docs/reference/query-dsl/filters/indices-filter.asciidoc deleted file mode 100644 index 05ad2327276..00000000000 --- a/docs/reference/query-dsl/filters/indices-filter.asciidoc +++ /dev/null @@ -1,37 +0,0 @@ -[[query-dsl-indices-filter]] -=== Indices Filter - -The `indices` filter can be used when executed across multiple indices, -allowing to have a filter that executes only when executed on an index -that matches a specific list of indices, and another filter that executes -when it is executed on an index that does not match the listed indices. - -[source,js] --------------------------------------------------- -{ - "indices" : { - "indices" : ["index1", "index2"], - "filter" : { - "term" : { "tag" : "wow" } - }, - "no_match_filter" : { - "term" : { "tag" : "kow" } - } - } -} --------------------------------------------------- - -You can use the `index` field to provide a single index. - -`no_match_filter` can also have "string" value of `none` (to match no -documents), and `all` (to match all). Defaults to `all`. - -`filter` is mandatory, as well as `indices` (or `index`). - -[TIP] -=================================================================== -The fields order is important: if the `indices` are provided before `filter` -or `no_match_filter`, the related filters get parsed only against the indices -that they are going to be executed on. This is useful to avoid parsing filters -when it is not necessary and prevent potential mapping errors. -=================================================================== diff --git a/docs/reference/query-dsl/filters/match-all-filter.asciidoc b/docs/reference/query-dsl/filters/match-all-filter.asciidoc deleted file mode 100644 index 97adbd1fb2a..00000000000 --- a/docs/reference/query-dsl/filters/match-all-filter.asciidoc +++ /dev/null @@ -1,15 +0,0 @@ -[[query-dsl-match-all-filter]] -=== Match All Filter - -A filter that matches on all documents: - -[source,js] --------------------------------------------------- -{ - "constant_score" : { - "filter" : { - "match_all" : { } - } - } -} --------------------------------------------------- diff --git a/docs/reference/query-dsl/filters/nested-filter.asciidoc b/docs/reference/query-dsl/filters/nested-filter.asciidoc deleted file mode 100644 index 41e14cd00c4..00000000000 --- a/docs/reference/query-dsl/filters/nested-filter.asciidoc +++ /dev/null @@ -1,74 +0,0 @@ -[[query-dsl-nested-filter]] -=== Nested Filter - -A `nested` filter works in a similar fashion to the -<> query. For example: - -[source,js] --------------------------------------------------- -{ - "filtered" : { - "query" : { "match_all" : {} }, - "filter" : { - "nested" : { - "path" : "obj1", - "filter" : { - "bool" : { - "must" : [ - { - "term" : {"obj1.name" : "blue"} - }, - { - "range" : {"obj1.count" : {"gt" : 5}} - } - ] - } - } - } - } - } -} --------------------------------------------------- - -[float] -==== Join option - -The nested filter also supports a `join` option which controls whether to perform the block join or not. -By default, it's enabled. But when it's disabled, it emits the hidden nested documents as hits instead of the joined root document. - -This is useful when a `nested` filter is used in a facet where nested is enabled, like you can see in the example below: - -[source,js] --------------------------------------------------- -{ - "query" : { - "nested" : { - "path" : "offers", - "query" : { - "match" : { - "offers.color" : "blue" - } - } - } - }, - "facets" : { - "size" : { - "terms" : { - "field" : "offers.size" - }, - "facet_filter" : { - "nested" : { - "path" : "offers", - "query" : { - "match" : { - "offers.color" : "blue" - } - }, - "join" : false - } - }, - "nested" : "offers" - } - } -}' --------------------------------------------------- diff --git a/docs/reference/query-dsl/filters/prefix-filter.asciidoc b/docs/reference/query-dsl/filters/prefix-filter.asciidoc deleted file mode 100644 index 964d9f42ba2..00000000000 --- a/docs/reference/query-dsl/filters/prefix-filter.asciidoc +++ /dev/null @@ -1,18 +0,0 @@ -[[query-dsl-prefix-filter]] -=== Prefix Filter - -Filters documents that have fields containing terms with a specified -prefix (*not analyzed*). Similar to prefix query, except that it acts as -a filter. Can be placed within queries that accept a filter. - -[source,js] --------------------------------------------------- -{ - "constant_score" : { - "filter" : { - "prefix" : { "user" : "ki" } - } - } -} --------------------------------------------------- - diff --git a/docs/reference/query-dsl/filters/query-filter.asciidoc b/docs/reference/query-dsl/filters/query-filter.asciidoc deleted file mode 100644 index 8df0f3c3b11..00000000000 --- a/docs/reference/query-dsl/filters/query-filter.asciidoc +++ /dev/null @@ -1,21 +0,0 @@ -[[query-dsl-query-filter]] -=== Query Filter - -Wraps any query to be used as a filter. Can be placed within queries -that accept a filter. - -[source,js] --------------------------------------------------- -{ - "constantScore" : { - "filter" : { - "query" : { - "query_string" : { - "query" : "this AND that OR thus" - } - } - } - } -} --------------------------------------------------- - diff --git a/docs/reference/query-dsl/filters/range-filter.asciidoc b/docs/reference/query-dsl/filters/range-filter.asciidoc deleted file mode 100644 index 0c84f91e196..00000000000 --- a/docs/reference/query-dsl/filters/range-filter.asciidoc +++ /dev/null @@ -1,97 +0,0 @@ -[[query-dsl-range-filter]] -=== Range Filter - -Filters documents with fields that have terms within a certain range. -Similar to <>, except that it acts as a filter. Can be placed within queries -that accept a filter. - -[source,js] --------------------------------------------------- -{ - "constant_score" : { - "filter" : { - "range" : { - "age" : { - "gte": 10, - "lte": 20 - } - } - } - } -} --------------------------------------------------- - -The `range` filter accepts the following parameters: - -[horizontal] -`gte`:: Greater-than or equal to -`gt`:: Greater-than -`lte`:: Less-than or equal to -`lt`:: Less-than - -[float] -==== Date options - -When applied on `date` fields the `range` filter accepts also a `time_zone` parameter. -The `time_zone` parameter will be applied to your input lower and upper bounds and will -move them to UTC time based date: - -[source,js] --------------------------------------------------- -{ - "constant_score": { - "filter": { - "range" : { - "born" : { - "gte": "2012-01-01", - "lte": "now", - "time_zone": "+1:00" - } - } - } - } -} --------------------------------------------------- - -In the above example, `gte` will be actually moved to `2011-12-31T23:00:00` UTC date. - -NOTE: if you give a date with a timezone explicitly defined and use the `time_zone` parameter, `time_zone` will be -ignored. For example, setting `gte` to `2012-01-01T00:00:00+01:00` with `"time_zone":"+10:00"` will still use `+01:00` time zone. - -When applied on `date` fields the `range` filter accepts also a `format` parameter. -The `format` parameter will help support another date format than the one defined in mapping: - -[source,js] --------------------------------------------------- -{ - "constant_score": { - "filter": { - "range" : { - "born" : { - "gte": "01/01/2012", - "lte": "2013", - "format": "dd/MM/yyyy||yyyy" - } - } - } - } -} --------------------------------------------------- - -[float] -==== Execution - -The `execution` option controls how the range filter internally executes. The `execution` option accepts the following values: - -[horizontal] -`index`:: Uses the field's inverted index in order to determine whether documents fall within the specified range. -`fielddata`:: Uses fielddata in order to determine whether documents fall within the specified range. - -In general for small ranges the `index` execution is faster and for longer ranges the `fielddata` execution is faster. - -The `fielddata` execution, as the name suggests, uses field data and therefore -requires more memory, so make sure you have sufficient memory on your nodes in -order to use this execution mode. It usually makes sense to use it on fields -you're already aggregating or sorting by. - diff --git a/docs/reference/query-dsl/filters/regexp-filter.asciidoc b/docs/reference/query-dsl/filters/regexp-filter.asciidoc deleted file mode 100644 index 06a45ae0739..00000000000 --- a/docs/reference/query-dsl/filters/regexp-filter.asciidoc +++ /dev/null @@ -1,59 +0,0 @@ -[[query-dsl-regexp-filter]] -=== Regexp Filter - -The `regexp` filter is similar to the -<> query, except -that it is cacheable and can speedup performance in case you are reusing -this filter in your queries. - -See <> for details of the supported regular expression language. - -[source,js] --------------------------------------------------- -{ - "filtered": { - "query": { - "match_all": {} - }, - "filter": { - "regexp":{ - "name.first" : "s.*y" - } - } - } -} --------------------------------------------------- - -You can also select the cache name and use the same regexp flags in the -filter as in the query. - -Regular expressions are dangerous because it's easy to accidentally -create an innocuous looking one that requires an exponential number of -internal determinized automaton states (and corresponding RAM and CPU) -for Lucene to execute. Lucene prevents these using the -`max_determinized_states` setting (defaults to 10000). You can raise -this limit to allow more complex regular expressions to execute. - -You have to enable caching explicitly in order to have the -`regexp` filter cached. - -[source,js] --------------------------------------------------- -{ - "filtered": { - "query": { - "match_all": {} - }, - "filter": { - "regexp":{ - "name.first" : { - "value" : "s.*y", - "flags" : "INTERSECTION|COMPLEMENT|EMPTY", - "max_determinized_states": 20000 - }, - "_name":"test" - } - } - } -} --------------------------------------------------- diff --git a/docs/reference/query-dsl/filters/term-filter.asciidoc b/docs/reference/query-dsl/filters/term-filter.asciidoc deleted file mode 100644 index 768fd94ac89..00000000000 --- a/docs/reference/query-dsl/filters/term-filter.asciidoc +++ /dev/null @@ -1,19 +0,0 @@ -[[query-dsl-term-filter]] -=== Term Filter - -Filters documents that have fields that contain a term (*not analyzed*). -Similar to <>, -except that it acts as a filter. Can be placed within queries that -accept a filter, for example: - -[source,js] --------------------------------------------------- -{ - "constant_score" : { - "filter" : { - "term" : { "user" : "kimchy"} - } - } -} --------------------------------------------------- - diff --git a/docs/reference/query-dsl/queries/function-score-query.asciidoc b/docs/reference/query-dsl/function-score-query.asciidoc similarity index 98% rename from docs/reference/query-dsl/queries/function-score-query.asciidoc rename to docs/reference/query-dsl/function-score-query.asciidoc index 8b742bb088d..4588b4c7858 100644 --- a/docs/reference/query-dsl/queries/function-score-query.asciidoc +++ b/docs/reference/query-dsl/function-score-query.asciidoc @@ -1,12 +1,12 @@ [[query-dsl-function-score-query]] -=== Function Score Query +== Function Score Query The `function_score` allows you to modify the score of documents that are retrieved by a query. This can be useful if, for example, a score function is computationally expensive and it is sufficient to compute the score on a filtered set of documents. -==== Using function score +=== Using function score To use `function_score`, the user has to define a query and one or several functions, that compute a new score for each document returned @@ -17,7 +17,7 @@ by the query. [source,js] -------------------------------------------------- "function_score": { - "(query|filter)": {}, + "query": {}, "boost": "boost for the whole query", "FUNCTION": {}, "boost_mode":"(multiply|replace|...)" @@ -26,12 +26,12 @@ by the query. Furthermore, several functions can be combined. In this case one can optionally choose to apply the function only if a document matches a -given filter: +given filtering query [source,js] -------------------------------------------------- "function_score": { - "(query|filter)": {}, + "query": {}, "boost": "boost for the whole query", "functions": [ { @@ -54,7 +54,9 @@ given filter: } -------------------------------------------------- -If no filter is given with a function this is equivalent to specifying +NOTE: The scores produced by the filtering query of each function do not matter. + +If no query is given with a function this is equivalent to specifying `"match_all": {}` First, each document is scored by the defined functions. The parameter diff --git a/docs/reference/query-dsl/queries/fuzzy-query.asciidoc b/docs/reference/query-dsl/fuzzy-query.asciidoc similarity index 96% rename from docs/reference/query-dsl/queries/fuzzy-query.asciidoc rename to docs/reference/query-dsl/fuzzy-query.asciidoc index b8af3aee066..0da33928855 100644 --- a/docs/reference/query-dsl/queries/fuzzy-query.asciidoc +++ b/docs/reference/query-dsl/fuzzy-query.asciidoc @@ -1,10 +1,10 @@ [[query-dsl-fuzzy-query]] -=== Fuzzy Query +== Fuzzy Query The fuzzy query uses similarity based on Levenshtein edit distance for `string` fields, and a `+/-` margin on numeric and date fields. -==== String fields +=== String fields The `fuzzy` query generates all possible matching terms that are within the maximum edit distance specified in `fuzziness` and then checks the term @@ -38,7 +38,7 @@ Or with more advanced settings: -------------------------------------------------- [float] -===== Parameters +==== Parameters [horizontal] `fuzziness`:: @@ -62,7 +62,7 @@ are both set to `0`. This could cause every term in the index to be examined! [float] -==== Numeric and date fields +=== Numeric and date fields Performs a <> ``around'' the value using the `fuzziness` value as a `+/-` range, where: diff --git a/docs/reference/query-dsl/filters/geo-bounding-box-filter.asciidoc b/docs/reference/query-dsl/geo-bounding-box-query.asciidoc similarity index 94% rename from docs/reference/query-dsl/filters/geo-bounding-box-filter.asciidoc rename to docs/reference/query-dsl/geo-bounding-box-query.asciidoc index 748756d7857..deb0727d61f 100644 --- a/docs/reference/query-dsl/filters/geo-bounding-box-filter.asciidoc +++ b/docs/reference/query-dsl/geo-bounding-box-query.asciidoc @@ -1,7 +1,7 @@ -[[query-dsl-geo-bounding-box-filter]] -=== Geo Bounding Box Filter +[[query-dsl-geo-bounding-box-query]] +== Geo Bounding Box Query -A filter allowing to filter hits based on a point location using a +A query allowing to filter hits based on a point location using a bounding box. Assuming the following indexed document: [source,js] @@ -45,13 +45,13 @@ Then the following simple query can be executed with a -------------------------------------------------- [float] -==== Accepted Formats +=== Accepted Formats In much the same way the geo_point type can accept different representation of the geo point, the filter can accept it as well: [float] -===== Lat Lon As Properties +==== Lat Lon As Properties [source,js] -------------------------------------------------- @@ -79,7 +79,7 @@ representation of the geo point, the filter can accept it as well: -------------------------------------------------- [float] -===== Lat Lon As Array +==== Lat Lon As Array Format in `[lon, lat]`, note, the order of lon/lat here in order to conform with http://geojson.org/[GeoJSON]. @@ -104,7 +104,7 @@ conform with http://geojson.org/[GeoJSON]. -------------------------------------------------- [float] -===== Lat Lon As String +==== Lat Lon As String Format in `lat,lon`. @@ -128,7 +128,7 @@ Format in `lat,lon`. -------------------------------------------------- [float] -===== Geohash +==== Geohash [source,js] -------------------------------------------------- @@ -150,7 +150,7 @@ Format in `lat,lon`. -------------------------------------------------- [float] -==== Vertices +=== Vertices The vertices of the bounding box can either be set by `top_left` and `bottom_right` or by `top_right` and `bottom_left` parameters. More @@ -182,20 +182,20 @@ values separately. [float] -==== geo_point Type +=== geo_point Type The filter *requires* the `geo_point` type to be set on the relevant field. [float] -==== Multi Location Per Document +=== Multi Location Per Document The filter can work with multiple locations / points per document. Once a single location / point matches the filter, the document will be included in the filter [float] -==== Type +=== Type The type of the bounding box execution by default is set to `memory`, which means in memory checks if the doc falls within the bounding box diff --git a/docs/reference/query-dsl/filters/geo-distance-filter.asciidoc b/docs/reference/query-dsl/geo-distance-query.asciidoc similarity index 94% rename from docs/reference/query-dsl/filters/geo-distance-filter.asciidoc rename to docs/reference/query-dsl/geo-distance-query.asciidoc index c7647f6fc4d..2fe109afd76 100644 --- a/docs/reference/query-dsl/filters/geo-distance-filter.asciidoc +++ b/docs/reference/query-dsl/geo-distance-query.asciidoc @@ -1,5 +1,5 @@ -[[query-dsl-geo-distance-filter]] -=== Geo Distance Filter +[[query-dsl-geo-distance-query]] +== Geo Distance Query Filters documents that include only hits that exists within a specific distance from a geo point. Assuming the following indexed json: @@ -40,13 +40,13 @@ filter: -------------------------------------------------- [float] -==== Accepted Formats +=== Accepted Formats In much the same way the `geo_point` type can accept different representation of the geo point, the filter can accept it as well: [float] -===== Lat Lon As Properties +==== Lat Lon As Properties [source,js] -------------------------------------------------- @@ -69,7 +69,7 @@ representation of the geo point, the filter can accept it as well: -------------------------------------------------- [float] -===== Lat Lon As Array +==== Lat Lon As Array Format in `[lon, lat]`, note, the order of lon/lat here in order to conform with http://geojson.org/[GeoJSON]. @@ -92,7 +92,7 @@ conform with http://geojson.org/[GeoJSON]. -------------------------------------------------- [float] -===== Lat Lon As String +==== Lat Lon As String Format in `lat,lon`. @@ -114,7 +114,7 @@ Format in `lat,lon`. -------------------------------------------------- [float] -===== Geohash +==== Geohash [source,js] -------------------------------------------------- @@ -134,7 +134,7 @@ Format in `lat,lon`. -------------------------------------------------- [float] -==== Options +=== Options The following are options allowed on the filter: @@ -160,13 +160,13 @@ The following are options allowed on the filter: [float] -==== geo_point Type +=== geo_point Type The filter *requires* the `geo_point` type to be set on the relevant field. [float] -==== Multi Location Per Document +=== Multi Location Per Document The `geo_distance` filter can work with multiple locations / points per document. Once a single location / point matches the filter, the diff --git a/docs/reference/query-dsl/filters/geo-distance-range-filter.asciidoc b/docs/reference/query-dsl/geo-distance-range-query.asciidoc similarity index 85% rename from docs/reference/query-dsl/filters/geo-distance-range-filter.asciidoc rename to docs/reference/query-dsl/geo-distance-range-query.asciidoc index 6da05947023..8109f3c9452 100644 --- a/docs/reference/query-dsl/filters/geo-distance-range-filter.asciidoc +++ b/docs/reference/query-dsl/geo-distance-range-query.asciidoc @@ -1,5 +1,5 @@ -[[query-dsl-geo-distance-range-filter]] -=== Geo Distance Range Filter +[[query-dsl-geo-distance-range-query]] +== Geo Distance Range Query Filters documents that exists within a range from a specific point: @@ -25,6 +25,6 @@ Filters documents that exists within a range from a specific point: -------------------------------------------------- Supports the same point location parameter as the -<> +<> filter. And also support the common parameters for range (lt, lte, gt, gte, from, to, include_upper and include_lower). diff --git a/docs/reference/query-dsl/filters/geo-polygon-filter.asciidoc b/docs/reference/query-dsl/geo-polygon-query.asciidoc similarity index 91% rename from docs/reference/query-dsl/filters/geo-polygon-filter.asciidoc rename to docs/reference/query-dsl/geo-polygon-query.asciidoc index 22bcb3fce31..ea22643ebe6 100644 --- a/docs/reference/query-dsl/filters/geo-polygon-filter.asciidoc +++ b/docs/reference/query-dsl/geo-polygon-query.asciidoc @@ -1,7 +1,7 @@ -[[query-dsl-geo-polygon-filter]] -=== Geo Polygon Filter +[[query-dsl-geo-polygon-query]] +== Geo Polygon Query -A filter allowing to include hits that only fall within a polygon of +A query allowing to include hits that only fall within a polygon of points. Here is an example: [source,js] @@ -27,10 +27,10 @@ points. Here is an example: -------------------------------------------------- [float] -==== Allowed Formats +=== Allowed Formats [float] -===== Lat Long as Array +==== Lat Long as Array Format in `[lon, lat]`, note, the order of lon/lat here in order to conform with http://geojson.org/[GeoJSON]. @@ -58,7 +58,7 @@ conform with http://geojson.org/[GeoJSON]. -------------------------------------------------- [float] -===== Lat Lon as String +==== Lat Lon as String Format in `lat,lon`. @@ -85,7 +85,7 @@ Format in `lat,lon`. -------------------------------------------------- [float] -===== Geohash +==== Geohash [source,js] -------------------------------------------------- @@ -110,7 +110,7 @@ Format in `lat,lon`. -------------------------------------------------- [float] -==== geo_point Type +=== geo_point Type The filter *requires* the <> type to be diff --git a/docs/reference/query-dsl/filters/geo-shape-filter.asciidoc b/docs/reference/query-dsl/geo-shape-query.asciidoc similarity index 94% rename from docs/reference/query-dsl/filters/geo-shape-filter.asciidoc rename to docs/reference/query-dsl/geo-shape-query.asciidoc index ca1df1ea995..0addabc342a 100644 --- a/docs/reference/query-dsl/filters/geo-shape-filter.asciidoc +++ b/docs/reference/query-dsl/geo-shape-query.asciidoc @@ -1,15 +1,12 @@ -[[query-dsl-geo-shape-filter]] -=== GeoShape Filter +[[query-dsl-geo-shape-query]] +== GeoShape Filter Filter documents indexed using the `geo_shape` type. Requires the <>. -You may also use the -<>. - -The `geo_shape` Filter uses the same grid square representation as the +The `geo_shape` query uses the same grid square representation as the geo_shape mapping to find documents that have a shape that intersects with the query shape. It will also use the same PrefixTree configuration as defined for the field mapping. diff --git a/docs/reference/query-dsl/filters/geohash-cell-filter.asciidoc b/docs/reference/query-dsl/geohash-cell-query.asciidoc similarity index 93% rename from docs/reference/query-dsl/filters/geohash-cell-filter.asciidoc rename to docs/reference/query-dsl/geohash-cell-query.asciidoc index 5f55936c616..b0004b64dee 100644 --- a/docs/reference/query-dsl/filters/geohash-cell-filter.asciidoc +++ b/docs/reference/query-dsl/geohash-cell-query.asciidoc @@ -1,7 +1,7 @@ -[[query-dsl-geohash-cell-filter]] -=== Geohash Cell Filter +[[query-dsl-geohash-cell-query]] +== Geohash Cell Query -The `geohash_cell` filter provides access to a hierarchy of geohashes. +The `geohash_cell` query provides access to a hierarchy of geohashes. By defining a geohash cell, only <> within this cell will match this filter. diff --git a/docs/reference/query-dsl/queries/has-child-query.asciidoc b/docs/reference/query-dsl/has-child-query.asciidoc similarity index 87% rename from docs/reference/query-dsl/queries/has-child-query.asciidoc rename to docs/reference/query-dsl/has-child-query.asciidoc index f161dd74842..873a934d711 100644 --- a/docs/reference/query-dsl/queries/has-child-query.asciidoc +++ b/docs/reference/query-dsl/has-child-query.asciidoc @@ -1,12 +1,9 @@ [[query-dsl-has-child-query]] -=== Has Child Query +== Has Child Query -The `has_child` query works the same as the -<> filter, -by automatically wrapping the filter with a -<> -(when using the default score type). It has the same syntax as the -<> filter: +The `has_child` filter accepts a query and the child type to run against, and +results in parent documents that have child docs matching the query. Here is +an example: [source,js] -------------------------------------------------- @@ -28,7 +25,7 @@ can be executed in one or more iteration. When using the `has_child` query the `total_hits` is always correct. [float] -==== Scoring capabilities +=== Scoring capabilities The `has_child` also has scoring support. The supported score types are `min`, `max`, `sum`, `avg` or `none`. The default is @@ -54,7 +51,7 @@ inside the `has_child` query: -------------------------------------------------- [float] -==== Min/Max Children +=== Min/Max Children The `has_child` query allows you to specify that a minimum and/or maximum number of children are required to match for the parent doc to be considered @@ -82,7 +79,7 @@ The `min_children` and `max_children` parameters can be combined with the `score_mode` parameter. [float] -==== Memory Considerations +=== Memory Considerations In order to support parent-child joins, all of the (string) parent IDs must be resident in memory (in the <>. diff --git a/docs/reference/query-dsl/queries/has-parent-query.asciidoc b/docs/reference/query-dsl/has-parent-query.asciidoc similarity index 81% rename from docs/reference/query-dsl/queries/has-parent-query.asciidoc rename to docs/reference/query-dsl/has-parent-query.asciidoc index 3e66e6f5b0c..9c31fd179e0 100644 --- a/docs/reference/query-dsl/queries/has-parent-query.asciidoc +++ b/docs/reference/query-dsl/has-parent-query.asciidoc @@ -1,12 +1,11 @@ [[query-dsl-has-parent-query]] -=== Has Parent Query +== Has Parent Query -The `has_parent` query works the same as the -<> -filter, by automatically wrapping the filter with a constant_score (when -using the default score type). It has the same syntax as the -<> -filter. +The `has_parent` query accepts a query and a parent type. The query is +executed in the parent document space, which is specified by the parent +type. This query returns child documents which associated parents have +matched. For the rest `has_parent` query has the same options and works +in the same manner as the `has_child` query. [source,js] -------------------------------------------------- @@ -23,7 +22,7 @@ filter. -------------------------------------------------- [float] -==== Scoring capabilities +=== Scoring capabilities The `has_parent` also has scoring support. The supported score types are `score` or `none`. The default is `none` and @@ -50,7 +49,7 @@ matching parent document. The score type can be specified with the -------------------------------------------------- [float] -==== Memory Considerations +=== Memory Considerations In order to support parent-child joins, all of the (string) parent IDs must be resident in memory (in the <>. diff --git a/docs/reference/query-dsl/queries/ids-query.asciidoc b/docs/reference/query-dsl/ids-query.asciidoc similarity index 84% rename from docs/reference/query-dsl/queries/ids-query.asciidoc rename to docs/reference/query-dsl/ids-query.asciidoc index 8de62d7a3e9..e5f1441f317 100644 --- a/docs/reference/query-dsl/queries/ids-query.asciidoc +++ b/docs/reference/query-dsl/ids-query.asciidoc @@ -1,7 +1,7 @@ [[query-dsl-ids-query]] -=== Ids Query +== Ids Query -Filters documents that only have the provided ids. Note, this filter +Filters documents that only have the provided ids. Note, this query does not require the <> field to be indexed since it works using the <> field. diff --git a/docs/reference/query-dsl/index.asciidoc b/docs/reference/query-dsl/index.asciidoc new file mode 100644 index 00000000000..9f102f53482 --- /dev/null +++ b/docs/reference/query-dsl/index.asciidoc @@ -0,0 +1,97 @@ +include::match-query.asciidoc[] + +include::multi-match-query.asciidoc[] + +include::and-query.asciidoc[] + +include::bool-query.asciidoc[] + +include::boosting-query.asciidoc[] + +include::common-terms-query.asciidoc[] + +include::constant-score-query.asciidoc[] + +include::dis-max-query.asciidoc[] + +include::filtered-query.asciidoc[] + +include::function-score-query.asciidoc[] + +include::fuzzy-query.asciidoc[] + +include::geo-shape-query.asciidoc[] + +include::geo-bounding-box-query.asciidoc[] + +include::geo-distance-query.asciidoc[] + +include::geo-distance-range-query.asciidoc[] + +include::geohash-cell-query.asciidoc[] + +include::geo-polygon-query.asciidoc[] + +include::has-child-query.asciidoc[] + +include::has-parent-query.asciidoc[] + +include::ids-query.asciidoc[] + +include::indices-query.asciidoc[] + +include::limit-query.asciidoc[] + +include::match-all-query.asciidoc[] + +include::mlt-query.asciidoc[] + +include::nested-query.asciidoc[] + +include::not-query.asciidoc[] + +include::or-query.asciidoc[] + +include::prefix-query.asciidoc[] + +include::query-string-query.asciidoc[] + +include::simple-query-string-query.asciidoc[] + +include::range-query.asciidoc[] + +include::regexp-query.asciidoc[] + +include::span-containing-query.asciidoc[] + +include::span-first-query.asciidoc[] + +include::span-multi-term-query.asciidoc[] + +include::span-near-query.asciidoc[] + +include::span-not-query.asciidoc[] + +include::span-or-query.asciidoc[] + +include::span-term-query.asciidoc[] + +include::span-within-query.asciidoc[] + +include::term-query.asciidoc[] + +include::terms-query.asciidoc[] + +include::top-children-query.asciidoc[] + +include::wildcard-query.asciidoc[] + +include::minimum-should-match.asciidoc[] + +include::multi-term-rewrite.asciidoc[] + +include::script-query.asciidoc[] + +include::template-query.asciidoc[] + +include::type-query.asciidoc[] diff --git a/docs/reference/query-dsl/queries/indices-query.asciidoc b/docs/reference/query-dsl/indices-query.asciidoc similarity index 98% rename from docs/reference/query-dsl/queries/indices-query.asciidoc rename to docs/reference/query-dsl/indices-query.asciidoc index c5978338d14..651d3f22f61 100644 --- a/docs/reference/query-dsl/queries/indices-query.asciidoc +++ b/docs/reference/query-dsl/indices-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-indices-query]] -=== Indices Query +== Indices Query The `indices` query can be used when executed across multiple indices, allowing to have a query that executes only when executed on an index diff --git a/docs/reference/query-dsl/filters/limit-filter.asciidoc b/docs/reference/query-dsl/limit-query.asciidoc similarity index 76% rename from docs/reference/query-dsl/filters/limit-filter.asciidoc rename to docs/reference/query-dsl/limit-query.asciidoc index 950c5a93b0b..52140296c2c 100644 --- a/docs/reference/query-dsl/filters/limit-filter.asciidoc +++ b/docs/reference/query-dsl/limit-query.asciidoc @@ -1,9 +1,9 @@ -[[query-dsl-limit-filter]] -=== Limit Filter +[[query-dsl-limit-query]] +== Limit Query deprecated[1.6.0, Use <> instead] -A limit filter limits the number of documents (per shard) to execute on. +A limit query limits the number of documents (per shard) to execute on. For example: [source,js] diff --git a/docs/reference/query-dsl/queries/match-all-query.asciidoc b/docs/reference/query-dsl/match-all-query.asciidoc similarity index 95% rename from docs/reference/query-dsl/queries/match-all-query.asciidoc rename to docs/reference/query-dsl/match-all-query.asciidoc index 2ea3d410bfd..85b0a2ff95e 100644 --- a/docs/reference/query-dsl/queries/match-all-query.asciidoc +++ b/docs/reference/query-dsl/match-all-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-match-all-query]] -=== Match All Query +== Match All Query A query that matches all documents. Maps to Lucene `MatchAllDocsQuery`. diff --git a/docs/reference/query-dsl/queries/match-query.asciidoc b/docs/reference/query-dsl/match-query.asciidoc similarity index 99% rename from docs/reference/query-dsl/queries/match-query.asciidoc rename to docs/reference/query-dsl/match-query.asciidoc index 2ebb8e934e2..8925f2904a3 100644 --- a/docs/reference/query-dsl/queries/match-query.asciidoc +++ b/docs/reference/query-dsl/match-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-match-query]] -=== Match Query +== Match Query A family of `match` queries that accept text/numerics/dates, analyzes it, and constructs a query out of it. For example: diff --git a/docs/reference/query-dsl/queries/minimum-should-match.asciidoc b/docs/reference/query-dsl/minimum-should-match.asciidoc similarity index 99% rename from docs/reference/query-dsl/queries/minimum-should-match.asciidoc rename to docs/reference/query-dsl/minimum-should-match.asciidoc index 29718562ff1..d6395da95e4 100644 --- a/docs/reference/query-dsl/queries/minimum-should-match.asciidoc +++ b/docs/reference/query-dsl/minimum-should-match.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-minimum-should-match]] -=== Minimum Should Match +== Minimum Should Match The `minimum_should_match` parameter possible values: diff --git a/docs/reference/query-dsl/filters/missing-filter.asciidoc b/docs/reference/query-dsl/missing-query.asciidoc similarity index 96% rename from docs/reference/query-dsl/filters/missing-filter.asciidoc rename to docs/reference/query-dsl/missing-query.asciidoc index 6d455938f6a..906823291f9 100644 --- a/docs/reference/query-dsl/filters/missing-filter.asciidoc +++ b/docs/reference/query-dsl/missing-query.asciidoc @@ -1,5 +1,5 @@ -[[query-dsl-missing-filter]] -=== Missing Filter +[[query-dsl-missing-query]] +== Missing Query Returns documents that have only `null` values or no value in the original field: @@ -42,7 +42,7 @@ These documents would *not* match the above filter: <3> This field has one non-`null` value. [float] -==== `null_value` mapping +=== `null_value` mapping If the field mapping includes a `null_value` (see <>) then explicit `null` values are replaced with the specified `null_value`. For instance, if the `user` field were mapped @@ -75,7 +75,7 @@ no values in the `user` field and thus would match the `missing` filter: -------------------------------------------------- [float] -===== `existence` and `null_value` parameters +==== `existence` and `null_value` parameters When the field being queried has a `null_value` mapping, then the behaviour of the `missing` filter can be altered with the `existence` and `null_value` diff --git a/docs/reference/query-dsl/queries/mlt-query.asciidoc b/docs/reference/query-dsl/mlt-query.asciidoc similarity index 98% rename from docs/reference/query-dsl/queries/mlt-query.asciidoc rename to docs/reference/query-dsl/mlt-query.asciidoc index 37246db5023..d0097627e1d 100644 --- a/docs/reference/query-dsl/queries/mlt-query.asciidoc +++ b/docs/reference/query-dsl/mlt-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-mlt-query]] -=== More Like This Query +== More Like This Query The More Like This Query (MLT Query) finds documents that are "like" a given set of documents. In order to do so, MLT selects a set of representative terms @@ -87,7 +87,7 @@ present in the index, the syntax is similar to <> to allow multi-field queries: @@ -70,7 +70,7 @@ parameter, which can be set to: combines the `_score` from each field. See <>. [[type-best-fields]] -==== `best_fields` +=== `best_fields` The `best_fields` type is most useful when you are searching for multiple words best found in the same field. For instance ``brown fox'' in a single @@ -156,7 +156,7 @@ See <> for a better solution. ================================================== [[type-most-fields]] -==== `most_fields` +=== `most_fields` The `most_fields` type is most useful when querying multiple fields that contain the same text analyzed in different ways. For instance, the main @@ -203,7 +203,7 @@ and `cutoff_frequency`, as explained in <>, b *see <>*. [[type-phrase]] -==== `phrase` and `phrase_prefix` +=== `phrase` and `phrase_prefix` The `phrase` and `phrase_prefix` types behave just like <>, but they use a `match_phrase` or `match_phrase_prefix` query instead of a @@ -240,7 +240,7 @@ in <>. Type `phrase_prefix` additionally accepts `max_expansions`. [[type-cross-fields]] -==== `cross_fields` +=== `cross_fields` The `cross_fields` type is particularly useful with structured documents where multiple fields *should* match. For instance, when querying the `first_name` @@ -317,7 +317,7 @@ Also, accepts `analyzer`, `boost`, `operator`, `minimum_should_match`, `zero_terms_query` and `cutoff_frequency`, as explained in <>. -===== `cross_field` and analysis +==== `cross_field` and analysis The `cross_field` type can only work in term-centric mode on fields that have the same analyzer. Fields with the same analyzer are grouped together as in @@ -411,7 +411,7 @@ which will be executed as: blended("will", fields: [first, first.edge, last.edge, last]) blended("smith", fields: [first, first.edge, last.edge, last]) -===== `tie_breaker` +==== `tie_breaker` By default, each per-term `blended` query will use the best score returned by any field in a group, then these scores are added together to give the final diff --git a/docs/reference/query-dsl/queries/multi-term-rewrite.asciidoc b/docs/reference/query-dsl/multi-term-rewrite.asciidoc similarity index 98% rename from docs/reference/query-dsl/queries/multi-term-rewrite.asciidoc rename to docs/reference/query-dsl/multi-term-rewrite.asciidoc index 135be67a044..375e3eaa81f 100644 --- a/docs/reference/query-dsl/queries/multi-term-rewrite.asciidoc +++ b/docs/reference/query-dsl/multi-term-rewrite.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-multi-term-rewrite]] -=== Multi Term Query Rewrite +== Multi Term Query Rewrite Multi term queries, like <> and diff --git a/docs/reference/query-dsl/queries/nested-query.asciidoc b/docs/reference/query-dsl/nested-query.asciidoc similarity index 99% rename from docs/reference/query-dsl/queries/nested-query.asciidoc rename to docs/reference/query-dsl/nested-query.asciidoc index 6460e027885..27e6b620f38 100644 --- a/docs/reference/query-dsl/queries/nested-query.asciidoc +++ b/docs/reference/query-dsl/nested-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-nested-query]] -=== Nested Query +== Nested Query Nested query allows to query nested objects / docs (see <>). The diff --git a/docs/reference/query-dsl/filters/not-filter.asciidoc b/docs/reference/query-dsl/not-query.asciidoc similarity index 87% rename from docs/reference/query-dsl/filters/not-filter.asciidoc rename to docs/reference/query-dsl/not-query.asciidoc index ed533fc6d32..414722aaf2b 100644 --- a/docs/reference/query-dsl/filters/not-filter.asciidoc +++ b/docs/reference/query-dsl/not-query.asciidoc @@ -1,8 +1,7 @@ -[[query-dsl-not-filter]] -=== Not Filter +[[query-dsl-not-query]] +== Not Query -A filter that filters out matched documents using a query. Can be placed -within queries that accept a filter. +A query that filters out matched documents using a query. For example: [source,js] -------------------------------------------------- diff --git a/docs/reference/query-dsl/filters/or-filter.asciidoc b/docs/reference/query-dsl/or-query.asciidoc similarity index 68% rename from docs/reference/query-dsl/filters/or-filter.asciidoc rename to docs/reference/query-dsl/or-query.asciidoc index 890d30f38e0..ad85faabe3e 100644 --- a/docs/reference/query-dsl/filters/or-filter.asciidoc +++ b/docs/reference/query-dsl/or-query.asciidoc @@ -1,10 +1,10 @@ -[[query-dsl-or-filter]] -=== Or Filter +[[query-dsl-or-query]] +== Or Query -deprecated[2.0.0, Use the `bool` filter instead] +deprecated[2.0.0, Use the `bool` query instead] -A filter that matches documents using the `OR` boolean operator on other -filters. Can be placed within queries that accept a filter. +A query that matches documents using the `OR` boolean operator on other +queries. [source,js] -------------------------------------------------- diff --git a/docs/reference/query-dsl/queries/prefix-query.asciidoc b/docs/reference/query-dsl/prefix-query.asciidoc similarity index 98% rename from docs/reference/query-dsl/queries/prefix-query.asciidoc rename to docs/reference/query-dsl/prefix-query.asciidoc index cf26e850ad8..b1a3a1e9611 100644 --- a/docs/reference/query-dsl/queries/prefix-query.asciidoc +++ b/docs/reference/query-dsl/prefix-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-prefix-query]] -=== Prefix Query +== Prefix Query Matches documents that have fields containing terms with a specified prefix (*not analyzed*). The prefix query maps to Lucene `PrefixQuery`. diff --git a/docs/reference/query-dsl/queries.asciidoc b/docs/reference/query-dsl/queries.asciidoc deleted file mode 100644 index 20ce2789f7c..00000000000 --- a/docs/reference/query-dsl/queries.asciidoc +++ /dev/null @@ -1,83 +0,0 @@ -[[query-dsl-queries]] -== Queries - -As a general rule, queries should be used instead of filters: - -* for full text search -* where the result depends on a relevance score - -include::queries/match-query.asciidoc[] - -include::queries/multi-match-query.asciidoc[] - -include::queries/bool-query.asciidoc[] - -include::queries/boosting-query.asciidoc[] - -include::queries/common-terms-query.asciidoc[] - -include::queries/constant-score-query.asciidoc[] - -include::queries/dis-max-query.asciidoc[] - -include::queries/filtered-query.asciidoc[] - -include::queries/function-score-query.asciidoc[] - -include::queries/fuzzy-query.asciidoc[] - -include::queries/geo-shape-query.asciidoc[] - -include::queries/has-child-query.asciidoc[] - -include::queries/has-parent-query.asciidoc[] - -include::queries/ids-query.asciidoc[] - -include::queries/indices-query.asciidoc[] - -include::queries/match-all-query.asciidoc[] - -include::queries/mlt-query.asciidoc[] - -include::queries/nested-query.asciidoc[] - -include::queries/prefix-query.asciidoc[] - -include::queries/query-string-query.asciidoc[] - -include::queries/simple-query-string-query.asciidoc[] - -include::queries/range-query.asciidoc[] - -include::queries/regexp-query.asciidoc[] - -include::queries/span-containing-query.asciidoc[] - -include::queries/span-first-query.asciidoc[] - -include::queries/span-multi-term-query.asciidoc[] - -include::queries/span-near-query.asciidoc[] - -include::queries/span-not-query.asciidoc[] - -include::queries/span-or-query.asciidoc[] - -include::queries/span-term-query.asciidoc[] - -include::queries/span-within-query.asciidoc[] - -include::queries/term-query.asciidoc[] - -include::queries/terms-query.asciidoc[] - -include::queries/top-children-query.asciidoc[] - -include::queries/wildcard-query.asciidoc[] - -include::queries/minimum-should-match.asciidoc[] - -include::queries/multi-term-rewrite.asciidoc[] - -include::queries/template-query.asciidoc[] diff --git a/docs/reference/query-dsl/queries/constant-score-query.asciidoc b/docs/reference/query-dsl/queries/constant-score-query.asciidoc deleted file mode 100644 index 06ed6f767cb..00000000000 --- a/docs/reference/query-dsl/queries/constant-score-query.asciidoc +++ /dev/null @@ -1,36 +0,0 @@ -[[query-dsl-constant-score-query]] -=== Constant Score Query - -A query that wraps a filter or another query and simply returns a -constant score equal to the query boost for every document in the -filter. Maps to Lucene `ConstantScoreQuery`. - -[source,js] --------------------------------------------------- -{ - "constant_score" : { - "filter" : { - "term" : { "user" : "kimchy"} - }, - "boost" : 1.2 - } -} --------------------------------------------------- - -The filter object can hold only filter elements, not queries. Filters -can be much faster compared to queries since they don't perform any -scoring, especially when they are cached. - -A query can also be wrapped in a `constant_score` query: - -[source,js] --------------------------------------------------- -{ - "constant_score" : { - "query" : { - "term" : { "user" : "kimchy"} - }, - "boost" : 1.2 - } -} --------------------------------------------------- diff --git a/docs/reference/query-dsl/queries/geo-shape-query.asciidoc b/docs/reference/query-dsl/queries/geo-shape-query.asciidoc deleted file mode 100644 index 94cd0391baa..00000000000 --- a/docs/reference/query-dsl/queries/geo-shape-query.asciidoc +++ /dev/null @@ -1,49 +0,0 @@ -[[query-dsl-geo-shape-query]] -=== GeoShape Query - -Query version of the -<>. - -Requires the <>. - -Given a document that looks like this: - -[source,js] --------------------------------------------------- -{ - "name": "Wind & Wetter, Berlin, Germany", - "location": { - "type": "Point", - "coordinates": [13.400544, 52.530286] - } -} --------------------------------------------------- - -The following query will find the point: - -[source,js] --------------------------------------------------- -{ - "query": { - "geo_shape": { - "location": { - "shape": { - "type": "envelope", - "coordinates": [[13, 53],[14, 52]] - } - } - } - } -} --------------------------------------------------- - -See the Filter's documentation for more information. - -[float] -==== Relevancy and Score - -Currently Elasticsearch does not have any notion of geo shape relevancy, -consequently the Query internally uses a `constant_score` Query which -wraps a <>. diff --git a/docs/reference/query-dsl/queries/terms-query.asciidoc b/docs/reference/query-dsl/queries/terms-query.asciidoc deleted file mode 100644 index a1f62a3d2cc..00000000000 --- a/docs/reference/query-dsl/queries/terms-query.asciidoc +++ /dev/null @@ -1,19 +0,0 @@ -[[query-dsl-terms-query]] -=== Terms Query - -A query that match on any (configurable) of the provided terms. This is -a simpler syntax query for using a `bool` query with several `term` -queries in the `should` clauses. For example: - -[source,js] --------------------------------------------------- -{ - "terms" : { - "tags" : [ "blue", "pill" ], - "minimum_should_match" : 1 - } -} --------------------------------------------------- - -The `terms` query is also aliased with `in` as the query name for -simpler usage. diff --git a/docs/reference/query-dsl/queries/query-string-query.asciidoc b/docs/reference/query-dsl/query-string-query.asciidoc similarity index 99% rename from docs/reference/query-dsl/queries/query-string-query.asciidoc rename to docs/reference/query-dsl/query-string-query.asciidoc index 0f0763f65c5..9df7998c961 100644 --- a/docs/reference/query-dsl/queries/query-string-query.asciidoc +++ b/docs/reference/query-dsl/query-string-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-query-string-query]] -=== Query String Query +== Query String Query A query that uses a query parser in order to parse its content. Here is an example: @@ -89,7 +89,7 @@ rewritten using the parameter. [float] -==== Default Field +=== Default Field When not explicitly specifying the field to search on in the query string syntax, the `index.query.default_field` will be used to derive @@ -99,7 +99,7 @@ So, if `_all` field is disabled, it might make sense to change it to set a different default field. [float] -==== Multi Field +=== Multi Field The `query_string` query can also run against multiple fields. Fields can be provided via the `"fields"` parameter (example below). diff --git a/docs/reference/query-dsl/queries/query-string-syntax.asciidoc b/docs/reference/query-dsl/query-string-syntax.asciidoc similarity index 96% rename from docs/reference/query-dsl/queries/query-string-syntax.asciidoc rename to docs/reference/query-dsl/query-string-syntax.asciidoc index 6371af76508..d1f3be8c0db 100644 --- a/docs/reference/query-dsl/queries/query-string-syntax.asciidoc +++ b/docs/reference/query-dsl/query-string-syntax.asciidoc @@ -1,6 +1,6 @@ [[query-string-syntax]] -==== Query string syntax +=== Query string syntax The query string ``mini-language'' is used by the <> and by the @@ -14,7 +14,7 @@ phrase, in the same order. Operators allow you to customize the search -- the available options are explained below. -===== Field names +==== Field names As mentioned in <>, the `default_field` is searched for the search terms, but it is possible to specify other fields in the query syntax: @@ -46,7 +46,7 @@ search terms, but it is possible to specify other fields in the query syntax: _exists_:title -===== Wildcards +==== Wildcards Wildcard searches can be run on individual terms, using `?` to replace a single character, and `*` to replace zero or more characters: @@ -72,7 +72,7 @@ is missing some of its letters. However, by setting `analyze_wildcard` to `true`, an attempt will be made to analyze wildcarded words before searching the term list for matching terms. -===== Regular expressions +==== Regular expressions Regular expression patterns can be embedded in the query string by wrapping them in forward-slashes (`"/"`): @@ -92,7 +92,7 @@ Elasticsearch to visit every term in the index: Use with caution! ====== -===== Fuzziness +==== Fuzziness We can search for terms that are similar to, but not exactly like our search terms, using the ``fuzzy'' @@ -112,7 +112,7 @@ sufficient to catch 80% of all human misspellings. It can be specified as: quikc~1 -===== Proximity searches +==== Proximity searches While a phrase query (eg `"john smith"`) expects all of the terms in exactly the same order, a proximity query allows the specified words to be further @@ -127,7 +127,7 @@ query string, the more relevant that document is considered to be. When compared to the above example query, the phrase `"quick fox"` would be considered more relevant than `"quick brown fox"`. -===== Ranges +==== Ranges Ranges can be specified for date, numeric or string fields. Inclusive ranges are specified with square brackets `[min TO max]` and exclusive ranges with @@ -178,10 +178,10 @@ would need to join two clauses with an `AND` operator: =================================================================== The parsing of ranges in query strings can be complex and error prone. It is -much more reliable to use an explicit <>. +much more reliable to use an explicit <>. -===== Boosting +==== Boosting Use the _boost_ operator `^` to make one term more relevant than another. For instance, if we want to find all documents about foxes, but we are @@ -196,7 +196,7 @@ Boosts can also be applied to phrases or to groups: "john smith"^2 (foo bar)^4 -===== Boolean operators +==== Boolean operators By default, all terms are optional, as long as one term matches. A search for `foo bar baz` will find any document that contains one or more of @@ -256,7 +256,7 @@ would look like this: **** -===== Grouping +==== Grouping Multiple terms or clauses can be grouped together with parentheses, to form sub-queries: @@ -268,7 +268,7 @@ of a sub-query: status:(active OR pending) title:(full text search)^2 -===== Reserved characters +==== Reserved characters If you need to use any of the characters which function as operators in your query itself (and not as operators), then you should escape them with @@ -290,7 +290,7 @@ index is actually `"wifi"`. Escaping the space will protect it from being touched by the query string parser: `"wi\ fi"`. **** -===== Empty Query +==== Empty Query If the query string is empty or only contains whitespaces the query will yield an empty result set. diff --git a/docs/reference/query-dsl/queries/range-query.asciidoc b/docs/reference/query-dsl/range-query.asciidoc similarity index 98% rename from docs/reference/query-dsl/queries/range-query.asciidoc rename to docs/reference/query-dsl/range-query.asciidoc index 5d5bb6a308d..ba627129dab 100644 --- a/docs/reference/query-dsl/queries/range-query.asciidoc +++ b/docs/reference/query-dsl/range-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-range-query]] -=== Range Query +== Range Query Matches documents with fields that have terms within a certain range. The type of the Lucene query depends on the field type, for `string` @@ -30,7 +30,7 @@ The `range` query accepts the following parameters: `boost`:: Sets the boost value of the query, defaults to `1.0` [float] -==== Date options +=== Date options When applied on `date` fields the `range` filter accepts also a `time_zone` parameter. The `time_zone` parameter will be applied to your input lower and upper bounds and will diff --git a/docs/reference/query-dsl/queries/regexp-query.asciidoc b/docs/reference/query-dsl/regexp-query.asciidoc similarity index 99% rename from docs/reference/query-dsl/queries/regexp-query.asciidoc rename to docs/reference/query-dsl/regexp-query.asciidoc index 692caf43480..d0be5973b6c 100644 --- a/docs/reference/query-dsl/queries/regexp-query.asciidoc +++ b/docs/reference/query-dsl/regexp-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-regexp-query]] -=== Regexp Query +== Regexp Query The `regexp` query allows you to use regular expression term queries. See <> for details of the supported regular expression language. diff --git a/docs/reference/query-dsl/queries/regexp-syntax.asciidoc b/docs/reference/query-dsl/regexp-syntax.asciidoc similarity index 99% rename from docs/reference/query-dsl/queries/regexp-syntax.asciidoc rename to docs/reference/query-dsl/regexp-syntax.asciidoc index 328d171d363..51992591ea9 100644 --- a/docs/reference/query-dsl/queries/regexp-syntax.asciidoc +++ b/docs/reference/query-dsl/regexp-syntax.asciidoc @@ -1,5 +1,5 @@ [[regexp-syntax]] -==== Regular expression syntax +=== Regular expression syntax Regular expression queries are supported by the `regexp` and the `query_string` queries. The Lucene regular expression engine @@ -11,7 +11,7 @@ We will not attempt to explain regular expressions, but just explain the supported operators. ==== -===== Standard operators +==== Standard operators Anchoring:: + diff --git a/docs/reference/query-dsl/filters/script-filter.asciidoc b/docs/reference/query-dsl/script-query.asciidoc similarity index 90% rename from docs/reference/query-dsl/filters/script-filter.asciidoc rename to docs/reference/query-dsl/script-query.asciidoc index 2f49422d88a..899f176578e 100644 --- a/docs/reference/query-dsl/filters/script-filter.asciidoc +++ b/docs/reference/query-dsl/script-query.asciidoc @@ -1,7 +1,7 @@ -[[query-dsl-script-filter]] -=== Script Filter +[[query-dsl-script-query]] +== Script Query -A filter allowing to define +A query allowing to define <> as filters. For example: @@ -20,7 +20,7 @@ example: ---------------------------------------------- [float] -==== Custom Parameters +=== Custom Parameters Scripts are compiled and cached for faster execution. If the same script can be used, just with different parameters provider, it is preferable diff --git a/docs/reference/query-dsl/queries/simple-query-string-query.asciidoc b/docs/reference/query-dsl/simple-query-string-query.asciidoc similarity index 98% rename from docs/reference/query-dsl/queries/simple-query-string-query.asciidoc rename to docs/reference/query-dsl/simple-query-string-query.asciidoc index bff789fceed..338ee094fc0 100644 --- a/docs/reference/query-dsl/queries/simple-query-string-query.asciidoc +++ b/docs/reference/query-dsl/simple-query-string-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-simple-query-string-query]] -=== Simple Query String Query +== Simple Query String Query A query that uses the SimpleQueryParser to parse its context. Unlike the regular `query_string` query, the `simple_query_string` query will never @@ -73,7 +73,7 @@ In order to search for any of these special characters, they will need to be escaped with `\`. [float] -==== Default Field +=== Default Field When not explicitly specifying the field to search on in the query string syntax, the `index.query.default_field` will be used to derive which field to search on. It defaults to `_all` field. @@ -82,7 +82,7 @@ So, if `_all` field is disabled, it might make sense to change it to set a different default field. [float] -==== Multi Field +=== Multi Field The fields parameter can also include pattern based field names, allowing to automatically expand to the relevant fields (dynamically introduced fields included). For example: @@ -98,7 +98,7 @@ introduced fields included). For example: -------------------------------------------------- [float] -==== Flags +=== Flags `simple_query_string` support multiple flags to specify which parsing features should be enabled. It is specified as a `|`-delimited string with the `flags` parameter: diff --git a/docs/reference/query-dsl/queries/span-containing-query.asciidoc b/docs/reference/query-dsl/span-containing-query.asciidoc similarity index 96% rename from docs/reference/query-dsl/queries/span-containing-query.asciidoc rename to docs/reference/query-dsl/span-containing-query.asciidoc index 965bf855b6f..3a214858e06 100644 --- a/docs/reference/query-dsl/queries/span-containing-query.asciidoc +++ b/docs/reference/query-dsl/span-containing-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-span-containing-query]] -=== Span Containing Query +== Span Containing Query Returns matches which enclose another span query. The span containing query maps to Lucene `SpanContainingQuery`. Here is an example: diff --git a/docs/reference/query-dsl/queries/span-first-query.asciidoc b/docs/reference/query-dsl/span-first-query.asciidoc similarity index 96% rename from docs/reference/query-dsl/queries/span-first-query.asciidoc rename to docs/reference/query-dsl/span-first-query.asciidoc index 74fe7ff88ba..b01edea691d 100644 --- a/docs/reference/query-dsl/queries/span-first-query.asciidoc +++ b/docs/reference/query-dsl/span-first-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-span-first-query]] -=== Span First Query +== Span First Query Matches spans near the beginning of a field. The span first query maps to Lucene `SpanFirstQuery`. Here is an example: diff --git a/docs/reference/query-dsl/queries/span-multi-term-query.asciidoc b/docs/reference/query-dsl/span-multi-term-query.asciidoc similarity index 96% rename from docs/reference/query-dsl/queries/span-multi-term-query.asciidoc rename to docs/reference/query-dsl/span-multi-term-query.asciidoc index af3da5cf7dd..dfb75bcce61 100644 --- a/docs/reference/query-dsl/queries/span-multi-term-query.asciidoc +++ b/docs/reference/query-dsl/span-multi-term-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-span-multi-term-query]] -=== Span Multi Term Query +== Span Multi Term Query The `span_multi` query allows you to wrap a `multi term query` (one of wildcard, fuzzy, prefix, term, range or regexp query) as a `span query`, so diff --git a/docs/reference/query-dsl/queries/span-near-query.asciidoc b/docs/reference/query-dsl/span-near-query.asciidoc similarity index 97% rename from docs/reference/query-dsl/queries/span-near-query.asciidoc rename to docs/reference/query-dsl/span-near-query.asciidoc index 39982e2ba22..2e905fc8870 100644 --- a/docs/reference/query-dsl/queries/span-near-query.asciidoc +++ b/docs/reference/query-dsl/span-near-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-span-near-query]] -=== Span Near Query +== Span Near Query Matches spans which are near one another. One can specify _slop_, the maximum number of intervening unmatched positions, as well as whether diff --git a/docs/reference/query-dsl/queries/span-not-query.asciidoc b/docs/reference/query-dsl/span-not-query.asciidoc similarity index 95% rename from docs/reference/query-dsl/queries/span-not-query.asciidoc rename to docs/reference/query-dsl/span-not-query.asciidoc index abd6ef82a20..a23877f1a8b 100644 --- a/docs/reference/query-dsl/queries/span-not-query.asciidoc +++ b/docs/reference/query-dsl/span-not-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-span-not-query]] -=== Span Not Query +== Span Not Query Removes matches which overlap with another span query. The span not query maps to Lucene `SpanNotQuery`. Here is an example: @@ -38,4 +38,4 @@ Other top level options: `pre`:: If set the amount of tokens before the include span can't have overlap with the exclude span. `post`:: If set the amount of tokens after the include span can't have overlap with the exclude span. `dist`:: If set the amount of tokens from within the include span can't have overlap with the exclude span. Equivalent - of setting both `pre` and `post`. \ No newline at end of file + of setting both `pre` and `post`. diff --git a/docs/reference/query-dsl/queries/span-or-query.asciidoc b/docs/reference/query-dsl/span-or-query.asciidoc similarity index 96% rename from docs/reference/query-dsl/queries/span-or-query.asciidoc rename to docs/reference/query-dsl/span-or-query.asciidoc index 72a4ce8724b..10a168e3ac6 100644 --- a/docs/reference/query-dsl/queries/span-or-query.asciidoc +++ b/docs/reference/query-dsl/span-or-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-span-or-query]] -=== Span Or Query +== Span Or Query Matches the union of its span clauses. The span or query maps to Lucene `SpanOrQuery`. Here is an example: diff --git a/docs/reference/query-dsl/queries/span-term-query.asciidoc b/docs/reference/query-dsl/span-term-query.asciidoc similarity index 97% rename from docs/reference/query-dsl/queries/span-term-query.asciidoc rename to docs/reference/query-dsl/span-term-query.asciidoc index 9de86d48684..3efe4387efc 100644 --- a/docs/reference/query-dsl/queries/span-term-query.asciidoc +++ b/docs/reference/query-dsl/span-term-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-span-term-query]] -=== Span Term Query +== Span Term Query Matches spans containing a term. The span term query maps to Lucene `SpanTermQuery`. Here is an example: diff --git a/docs/reference/query-dsl/queries/span-within-query.asciidoc b/docs/reference/query-dsl/span-within-query.asciidoc similarity index 97% rename from docs/reference/query-dsl/queries/span-within-query.asciidoc rename to docs/reference/query-dsl/span-within-query.asciidoc index dc5c4bbfdfd..24510ac023c 100644 --- a/docs/reference/query-dsl/queries/span-within-query.asciidoc +++ b/docs/reference/query-dsl/span-within-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-span-within-query]] -=== Span Within Query +== Span Within Query Returns matches which are enclosed inside another span query. The span within query maps to Lucene `SpanWithinQuery`. Here is an example: diff --git a/docs/reference/query-dsl/queries/template-query.asciidoc b/docs/reference/query-dsl/template-query.asciidoc similarity index 98% rename from docs/reference/query-dsl/queries/template-query.asciidoc rename to docs/reference/query-dsl/template-query.asciidoc index 0eb43b3642c..5d68992ff54 100644 --- a/docs/reference/query-dsl/queries/template-query.asciidoc +++ b/docs/reference/query-dsl/template-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-template-query]] -=== Template Query +== Template Query A query that accepts a query template and a map of key/value pairs to fill in template parameters. Templating is based on Mustache. For simple token substitution all you provide @@ -56,7 +56,7 @@ GET /_search <1> New line characters (`\n`) should be escaped as `\\n` or removed, and quotes (`"`) should be escaped as `\\"`. -==== Stored templates +=== Stored templates You can register a template by storing it in the `config/scripts` directory, in a file using the `.mustache` extension. In order to execute the stored template, reference it by name in the `file` diff --git a/docs/reference/query-dsl/queries/term-query.asciidoc b/docs/reference/query-dsl/term-query.asciidoc similarity index 98% rename from docs/reference/query-dsl/queries/term-query.asciidoc rename to docs/reference/query-dsl/term-query.asciidoc index cd9537d9383..5b0acf6bace 100644 --- a/docs/reference/query-dsl/queries/term-query.asciidoc +++ b/docs/reference/query-dsl/term-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-term-query]] -=== Term Query +== Term Query Matches documents that have fields that contain a term (*not analyzed*). The term query maps to Lucene `TermQuery`. The following matches diff --git a/docs/reference/query-dsl/filters/terms-filter.asciidoc b/docs/reference/query-dsl/terms-query.asciidoc similarity index 96% rename from docs/reference/query-dsl/filters/terms-filter.asciidoc rename to docs/reference/query-dsl/terms-query.asciidoc index 027fc174db2..52092f17655 100644 --- a/docs/reference/query-dsl/filters/terms-filter.asciidoc +++ b/docs/reference/query-dsl/terms-query.asciidoc @@ -1,5 +1,5 @@ -[[query-dsl-terms-filter]] -=== Terms Filter +[[query-dsl-terms-query]] +== Terms Query Filters documents that have fields that match any of the provided terms (*not analyzed*). For example: @@ -15,7 +15,7 @@ Filters documents that have fields that match any of the provided terms } -------------------------------------------------- -The `terms` filter is also aliased with `in` as the filter name for +The `terms` query is also aliased with `in` as the filter name for simpler usage. [float] diff --git a/docs/reference/query-dsl/queries/top-children-query.asciidoc b/docs/reference/query-dsl/top-children-query.asciidoc similarity index 97% rename from docs/reference/query-dsl/queries/top-children-query.asciidoc rename to docs/reference/query-dsl/top-children-query.asciidoc index a4d74f62184..141ec4f7993 100644 --- a/docs/reference/query-dsl/queries/top-children-query.asciidoc +++ b/docs/reference/query-dsl/top-children-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-top-children-query]] -=== Top Children Query +== Top Children Query deprecated[1.6.0, Use the `has_child` query instead] @@ -45,7 +45,7 @@ including the default values: -------------------------------------------------- [float] -==== Scope +=== Scope A `_scope` can be defined on the query allowing to run aggregations on the same scope name that will work against the child documents. For example: @@ -66,7 +66,7 @@ same scope name that will work against the child documents. For example: -------------------------------------------------- [float] -==== Memory Considerations +=== Memory Considerations In order to support parent-child joins, all of the (string) parent IDs must be resident in memory (in the <>. diff --git a/docs/reference/query-dsl/filters/type-filter.asciidoc b/docs/reference/query-dsl/type-query.asciidoc similarity index 71% rename from docs/reference/query-dsl/filters/type-filter.asciidoc rename to docs/reference/query-dsl/type-query.asciidoc index 07bde382622..d4047f38a0c 100644 --- a/docs/reference/query-dsl/filters/type-filter.asciidoc +++ b/docs/reference/query-dsl/type-query.asciidoc @@ -1,8 +1,8 @@ -[[query-dsl-type-filter]] -=== Type Filter +[[query-dsl-type-query]] +== Type Query Filters documents matching the provided document / mapping type. Note, -this filter can work even when the `_type` field is not indexed (using +this query can work even when the `_type` field is not indexed (using the <> field). [source,js] diff --git a/docs/reference/query-dsl/queries/wildcard-query.asciidoc b/docs/reference/query-dsl/wildcard-query.asciidoc similarity index 98% rename from docs/reference/query-dsl/queries/wildcard-query.asciidoc rename to docs/reference/query-dsl/wildcard-query.asciidoc index d72dbec2481..9d4bc759f3d 100644 --- a/docs/reference/query-dsl/queries/wildcard-query.asciidoc +++ b/docs/reference/query-dsl/wildcard-query.asciidoc @@ -1,5 +1,5 @@ [[query-dsl-wildcard-query]] -=== Wildcard Query +== Wildcard Query Matches documents that have fields matching a wildcard expression (*not analyzed*). Supported wildcards are `*`, which matches any character diff --git a/src/main/java/org/apache/lucene/queryparser/classic/ExistsFieldQueryExtension.java b/src/main/java/org/apache/lucene/queryparser/classic/ExistsFieldQueryExtension.java index 7ca24668206..6cac629796f 100644 --- a/src/main/java/org/apache/lucene/queryparser/classic/ExistsFieldQueryExtension.java +++ b/src/main/java/org/apache/lucene/queryparser/classic/ExistsFieldQueryExtension.java @@ -21,7 +21,7 @@ package org.apache.lucene.queryparser.classic; import org.apache.lucene.search.ConstantScoreQuery; import org.apache.lucene.search.Query; -import org.elasticsearch.index.query.ExistsFilterParser; +import org.elasticsearch.index.query.ExistsQueryParser; import org.elasticsearch.index.query.QueryParseContext; /** @@ -33,6 +33,6 @@ public class ExistsFieldQueryExtension implements FieldQueryExtension { @Override public Query query(QueryParseContext parseContext, String queryText) { - return new ConstantScoreQuery(ExistsFilterParser.newFilter(parseContext, queryText, null)); + return new ConstantScoreQuery(ExistsQueryParser.newFilter(parseContext, queryText, null)); } } diff --git a/src/main/java/org/apache/lucene/queryparser/classic/MissingFieldQueryExtension.java b/src/main/java/org/apache/lucene/queryparser/classic/MissingFieldQueryExtension.java index c2212e97690..ed1b7043bc3 100644 --- a/src/main/java/org/apache/lucene/queryparser/classic/MissingFieldQueryExtension.java +++ b/src/main/java/org/apache/lucene/queryparser/classic/MissingFieldQueryExtension.java @@ -21,7 +21,7 @@ package org.apache.lucene.queryparser.classic; import org.apache.lucene.search.ConstantScoreQuery; import org.apache.lucene.search.Query; -import org.elasticsearch.index.query.MissingFilterParser; +import org.elasticsearch.index.query.MissingQueryParser; import org.elasticsearch.index.query.QueryParseContext; /** @@ -33,7 +33,7 @@ public class MissingFieldQueryExtension implements FieldQueryExtension { @Override public Query query(QueryParseContext parseContext, String queryText) { - return new ConstantScoreQuery(MissingFilterParser.newFilter(parseContext, queryText, - MissingFilterParser.DEFAULT_EXISTENCE_VALUE, MissingFilterParser.DEFAULT_NULL_VALUE, null)); + return new ConstantScoreQuery(MissingQueryParser.newFilter(parseContext, queryText, + MissingQueryParser.DEFAULT_EXISTENCE_VALUE, MissingQueryParser.DEFAULT_NULL_VALUE, null)); } } diff --git a/src/main/java/org/elasticsearch/action/admin/indices/alias/Alias.java b/src/main/java/org/elasticsearch/action/admin/indices/alias/Alias.java index 15cd244ba23..a9e4c777784 100644 --- a/src/main/java/org/elasticsearch/action/admin/indices/alias/Alias.java +++ b/src/main/java/org/elasticsearch/action/admin/indices/alias/Alias.java @@ -24,8 +24,12 @@ import org.elasticsearch.common.Nullable; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Streamable; -import org.elasticsearch.common.xcontent.*; -import org.elasticsearch.index.query.FilterBuilder; +import org.elasticsearch.common.xcontent.ToXContent; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.common.xcontent.XContentFactory; +import org.elasticsearch.common.xcontent.XContentParser; +import org.elasticsearch.common.xcontent.XContentType; +import org.elasticsearch.index.query.QueryBuilder; import java.io.IOException; import java.util.Map; @@ -97,7 +101,7 @@ public class Alias implements Streamable { /** * Associates a filter to the alias */ - public Alias filter(FilterBuilder filterBuilder) { + public Alias filter(QueryBuilder filterBuilder) { if (filterBuilder == null) { this.filter = null; return this; diff --git a/src/main/java/org/elasticsearch/action/admin/indices/alias/IndicesAliasesRequest.java b/src/main/java/org/elasticsearch/action/admin/indices/alias/IndicesAliasesRequest.java index 769d0389449..fd6819c7fc9 100644 --- a/src/main/java/org/elasticsearch/action/admin/indices/alias/IndicesAliasesRequest.java +++ b/src/main/java/org/elasticsearch/action/admin/indices/alias/IndicesAliasesRequest.java @@ -22,6 +22,7 @@ package org.elasticsearch.action.admin.indices.alias; import com.carrotsearch.hppc.cursors.ObjectCursor; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; + import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.AliasesRequest; import org.elasticsearch.action.CompositeIndicesRequest; @@ -37,7 +38,7 @@ import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.util.CollectionUtils; -import org.elasticsearch.index.query.FilterBuilder; +import org.elasticsearch.index.query.QueryBuilder; import java.io.IOException; import java.util.ArrayList; @@ -113,7 +114,7 @@ public class IndicesAliasesRequest extends AcknowledgedRequest sorts; private Boolean trackScores; @@ -70,14 +71,6 @@ public class PercolateSourceBuilder implements ToXContent { return this; } - /** - * Sets a filter to reduce the number of percolate queries to be evaluated. - */ - public PercolateSourceBuilder setFilterBuilder(FilterBuilder filterBuilder) { - this.filterBuilder = filterBuilder; - return this; - } - /** * Limits the maximum number of percolate query matches to be returned. */ @@ -149,10 +142,6 @@ public class PercolateSourceBuilder implements ToXContent { builder.field("query"); queryBuilder.toXContent(builder, params); } - if (filterBuilder != null) { - builder.field("filter"); - filterBuilder.toXContent(builder, params); - } if (size != null) { builder.field("size", size); } diff --git a/src/main/java/org/elasticsearch/action/search/SearchRequestBuilder.java b/src/main/java/org/elasticsearch/action/search/SearchRequestBuilder.java index 210329c7838..f7e84b0733a 100644 --- a/src/main/java/org/elasticsearch/action/search/SearchRequestBuilder.java +++ b/src/main/java/org/elasticsearch/action/search/SearchRequestBuilder.java @@ -28,7 +28,6 @@ import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentHelper; -import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.Scroll; @@ -236,7 +235,7 @@ public class SearchRequestBuilder extends ActionRequestBuilder leaves = reader.leaves(); List enums = Lists.newArrayListWithExpectedSize(leaves.size()); + final Weight weight; + if (filter == null) { + weight = null; + } else { + final IndexSearcher searcher = new IndexSearcher(reader); + searcher.setQueryCache(null); + weight = searcher.createNormalizedWeight(filter, false); + } for (LeafReaderContext context : leaves) { Terms terms = context.reader().terms(field); if (terms == null) { @@ -88,21 +98,23 @@ public class FilterableTermsEnum extends TermsEnum { continue; } Bits bits = null; - if (filter != null) { + if (weight != null) { // we want to force apply deleted docs - DocIdSet docIdSet = filter.getDocIdSet(context, context.reader().getLiveDocs()); - if (DocIdSets.isEmpty(docIdSet)) { + Scorer docs = weight.scorer(context, context.reader().getLiveDocs()); + if (docs == null) { // fully filtered, none matching, no need to iterate on this continue; } - bits = DocIdSets.toSafeBits(context.reader().maxDoc(), docIdSet); + + BitDocIdSet.Builder builder = new BitDocIdSet.Builder(context.reader().maxDoc()); + builder.or(docs); + bits = builder.build().bits(); + // Count how many docs are in our filtered set // TODO make this lazy-loaded only for those that need it? - DocIdSetIterator iterator = docIdSet.iterator(); - if (iterator != null) { - while (iterator.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) { - numDocs++; - } + docs = weight.scorer(context, context.reader().getLiveDocs()); + while (docs.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) { + numDocs++; } } enums.add(new Holder(termsEnum, bits)); diff --git a/src/main/java/org/elasticsearch/common/lucene/index/FreqTermsEnum.java b/src/main/java/org/elasticsearch/common/lucene/index/FreqTermsEnum.java index a74b1b74645..1db41c8e362 100644 --- a/src/main/java/org/elasticsearch/common/lucene/index/FreqTermsEnum.java +++ b/src/main/java/org/elasticsearch/common/lucene/index/FreqTermsEnum.java @@ -21,9 +21,8 @@ package org.elasticsearch.common.lucene.index; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.PostingsEnum; -import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.apache.lucene.util.BytesRef; -import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.lease.Releasable; import org.elasticsearch.common.lease.Releasables; @@ -48,7 +47,7 @@ public class FreqTermsEnum extends FilterableTermsEnum implements Releasable { private final boolean needTotalTermFreqs; - public FreqTermsEnum(IndexReader reader, String field, boolean needDocFreq, boolean needTotalTermFreq, @Nullable Filter filter, BigArrays bigArrays) throws IOException { + public FreqTermsEnum(IndexReader reader, String field, boolean needDocFreq, boolean needTotalTermFreq, @Nullable Query filter, BigArrays bigArrays) throws IOException { super(reader, field, needTotalTermFreq ? PostingsEnum.FREQS : PostingsEnum.NONE, filter); this.bigArrays = bigArrays; this.needDocFreqs = needDocFreq; diff --git a/src/main/java/org/elasticsearch/common/lucene/search/Queries.java b/src/main/java/org/elasticsearch/common/lucene/search/Queries.java index fe33206b0cc..19b94fc6d72 100644 --- a/src/main/java/org/elasticsearch/common/lucene/search/Queries.java +++ b/src/main/java/org/elasticsearch/common/lucene/search/Queries.java @@ -50,14 +50,6 @@ public class Queries { return new BooleanQuery(); } - public static Filter newMatchAllFilter() { - return new QueryWrapperFilter(newMatchAllQuery()); - } - - public static Filter newMatchNoDocsFilter() { - return new QueryWrapperFilter(newMatchNoDocsQuery()); - } - public static Filter newNestedFilter() { return new QueryWrapperFilter(new PrefixQuery(new Term(TypeFieldMapper.NAME, new BytesRef("__")))); } @@ -66,6 +58,13 @@ public class Queries { return new QueryWrapperFilter(not(newNestedFilter())); } + public static BooleanQuery filtered(Query query, Query filter) { + BooleanQuery bq = new BooleanQuery(); + bq.add(query, Occur.MUST); + bq.add(filter, Occur.FILTER); + return bq; + } + /** Return a query that matches all documents but those that match the given query. */ public static Query not(Query q) { BooleanQuery bq = new BooleanQuery(); diff --git a/src/main/java/org/elasticsearch/common/lucene/search/function/FiltersFunctionScoreQuery.java b/src/main/java/org/elasticsearch/common/lucene/search/function/FiltersFunctionScoreQuery.java index d1835f57098..4827d4927eb 100644 --- a/src/main/java/org/elasticsearch/common/lucene/search/function/FiltersFunctionScoreQuery.java +++ b/src/main/java/org/elasticsearch/common/lucene/search/function/FiltersFunctionScoreQuery.java @@ -37,10 +37,10 @@ import java.util.*; public class FiltersFunctionScoreQuery extends Query { public static class FilterFunction { - public final Filter filter; + public final Query filter; public final ScoreFunction function; - public FilterFunction(Filter filter, ScoreFunction function) { + public FilterFunction(Query filter, ScoreFunction function) { this.filter = filter; this.function = function; } diff --git a/src/main/java/org/elasticsearch/index/aliases/IndexAlias.java b/src/main/java/org/elasticsearch/index/aliases/IndexAlias.java index 01b1a011ca1..3d02731dbfa 100644 --- a/src/main/java/org/elasticsearch/index/aliases/IndexAlias.java +++ b/src/main/java/org/elasticsearch/index/aliases/IndexAlias.java @@ -19,7 +19,7 @@ package org.elasticsearch.index.aliases; -import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.compress.CompressedString; @@ -28,13 +28,13 @@ import org.elasticsearch.common.compress.CompressedString; */ public class IndexAlias { - private String alias; + private final String alias; - private CompressedString filter; + private final CompressedString filter; - private Filter parsedFilter; + private final Query parsedFilter; - public IndexAlias(String alias, @Nullable CompressedString filter, @Nullable Filter parsedFilter) { + public IndexAlias(String alias, @Nullable CompressedString filter, @Nullable Query parsedFilter) { this.alias = alias; this.filter = filter; this.parsedFilter = parsedFilter; @@ -50,7 +50,7 @@ public class IndexAlias { } @Nullable - public Filter parsedFilter() { + public Query parsedFilter() { return parsedFilter; } diff --git a/src/main/java/org/elasticsearch/index/aliases/IndexAliasesService.java b/src/main/java/org/elasticsearch/index/aliases/IndexAliasesService.java index 940344a627c..298501292e3 100644 --- a/src/main/java/org/elasticsearch/index/aliases/IndexAliasesService.java +++ b/src/main/java/org/elasticsearch/index/aliases/IndexAliasesService.java @@ -22,6 +22,7 @@ package org.elasticsearch.index.aliases; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.apache.lucene.search.QueryWrapperFilter; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.compress.CompressedString; @@ -33,7 +34,7 @@ import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.AbstractIndexComponent; import org.elasticsearch.index.Index; import org.elasticsearch.index.query.IndexQueryParserService; -import org.elasticsearch.index.query.ParsedFilter; +import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.index.settings.IndexSettings; import org.elasticsearch.indices.AliasFilterParsingException; import org.elasticsearch.indices.InvalidAliasNameException; @@ -82,7 +83,7 @@ public class IndexAliasesService extends AbstractIndexComponent implements Itera *

The list of filtering aliases should be obtained by calling MetaData.filteringAliases. * Returns null if no filtering is required.

*/ - public Filter aliasFilter(String... aliases) { + public Query aliasFilter(String... aliases) { if (aliases == null || aliases.length == 0) { return null; } @@ -109,7 +110,7 @@ public class IndexAliasesService extends AbstractIndexComponent implements Itera return null; } } - return new QueryWrapperFilter(combined); + return combined; } } @@ -121,15 +122,15 @@ public class IndexAliasesService extends AbstractIndexComponent implements Itera aliases.remove(alias); } - private Filter parse(String alias, CompressedString filter) { + private Query parse(String alias, CompressedString filter) { if (filter == null) { return null; } try { byte[] filterSource = filter.uncompressed(); try (XContentParser parser = XContentFactory.xContent(filterSource).createParser(filterSource)) { - ParsedFilter parsedFilter = indexQueryParser.parseInnerFilter(parser); - return parsedFilter == null ? null : parsedFilter.filter(); + ParsedQuery parsedFilter = indexQueryParser.parseInnerFilter(parser); + return parsedFilter == null ? null : parsedFilter.query(); } } catch (IOException ex) { throw new AliasFilterParsingException(index, alias, "Invalid alias filter", ex); diff --git a/src/main/java/org/elasticsearch/index/engine/Engine.java b/src/main/java/org/elasticsearch/index/engine/Engine.java index 24625a26cf1..3f0d10c2060 100644 --- a/src/main/java/org/elasticsearch/index/engine/Engine.java +++ b/src/main/java/org/elasticsearch/index/engine/Engine.java @@ -20,8 +20,16 @@ package org.elasticsearch.index.engine; import com.google.common.base.Preconditions; -import org.apache.lucene.index.*; -import org.apache.lucene.search.Filter; + +import org.apache.lucene.index.FilterLeafReader; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.IndexWriter; +import org.apache.lucene.index.LeafReader; +import org.apache.lucene.index.LeafReaderContext; +import org.apache.lucene.index.SegmentCommitInfo; +import org.apache.lucene.index.SegmentInfos; +import org.apache.lucene.index.SegmentReader; +import org.apache.lucene.index.Term; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.SearcherManager; @@ -52,7 +60,11 @@ import org.elasticsearch.index.translog.Translog; import java.io.Closeable; import java.io.IOException; -import java.util.*; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Condition; @@ -888,7 +900,7 @@ public abstract class Engine implements Closeable { private final Query query; private final BytesReference source; private final String[] filteringAliases; - private final Filter aliasFilter; + private final Query aliasFilter; private final String[] types; private final BitDocIdSetFilter parentFilter; private final Operation.Origin origin; @@ -896,7 +908,7 @@ public abstract class Engine implements Closeable { private final long startTime; private long endTime; - public DeleteByQuery(Query query, BytesReference source, @Nullable String[] filteringAliases, @Nullable Filter aliasFilter, BitDocIdSetFilter parentFilter, Operation.Origin origin, long startTime, String... types) { + public DeleteByQuery(Query query, BytesReference source, @Nullable String[] filteringAliases, @Nullable Query aliasFilter, BitDocIdSetFilter parentFilter, Operation.Origin origin, long startTime, String... types) { this.query = query; this.source = source; this.types = types; @@ -923,7 +935,7 @@ public abstract class Engine implements Closeable { return filteringAliases; } - public Filter aliasFilter() { + public Query aliasFilter() { return aliasFilter; } diff --git a/src/main/java/org/elasticsearch/index/engine/InternalEngine.java b/src/main/java/org/elasticsearch/index/engine/InternalEngine.java index dff9f7137df..95e3a202819 100644 --- a/src/main/java/org/elasticsearch/index/engine/InternalEngine.java +++ b/src/main/java/org/elasticsearch/index/engine/InternalEngine.java @@ -20,9 +20,26 @@ package org.elasticsearch.index.engine; import com.google.common.collect.Lists; -import org.apache.lucene.index.*; + +import org.apache.lucene.index.DirectoryReader; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriter.IndexReaderWarmer; -import org.apache.lucene.search.*; +import org.apache.lucene.index.IndexWriterConfig; +import org.apache.lucene.index.LeafReader; +import org.apache.lucene.index.LeafReaderContext; +import org.apache.lucene.index.LiveIndexWriterConfig; +import org.apache.lucene.index.MergePolicy; +import org.apache.lucene.index.MultiReader; +import org.apache.lucene.index.SegmentCommitInfo; +import org.apache.lucene.index.SegmentInfos; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.BooleanClause.Occur; +import org.apache.lucene.search.BooleanQuery; +import org.apache.lucene.search.IndexSearcher; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.SearcherFactory; +import org.apache.lucene.search.SearcherManager; import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.store.LockObtainFailedException; import org.apache.lucene.util.BytesRef; @@ -55,7 +72,11 @@ import org.elasticsearch.threadpool.ThreadPool; import java.io.FileNotFoundException; import java.io.IOException; -import java.util.*; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; @@ -595,15 +616,15 @@ public class InternalEngine extends Engine { private void innerDelete(DeleteByQuery delete) throws EngineException { try { - Query query; - if (delete.nested() && delete.aliasFilter() != null) { - query = new IncludeNestedDocsQuery(new FilteredQuery(delete.query(), delete.aliasFilter()), delete.parentFilter()); - } else if (delete.nested()) { - query = new IncludeNestedDocsQuery(delete.query(), delete.parentFilter()); - } else if (delete.aliasFilter() != null) { - query = new FilteredQuery(delete.query(), delete.aliasFilter()); - } else { - query = delete.query(); + Query query = delete.query(); + if (delete.aliasFilter() != null) { + BooleanQuery boolQuery = new BooleanQuery(); + boolQuery.add(query, Occur.MUST); + boolQuery.add(delete.aliasFilter(), Occur.FILTER); + query = boolQuery; + } + if (delete.nested()) { + query = new IncludeNestedDocsQuery(query, delete.parentFilter()); } indexWriter.deleteDocuments(query); diff --git a/src/main/java/org/elasticsearch/index/mapper/DocumentMapper.java b/src/main/java/org/elasticsearch/index/mapper/DocumentMapper.java index 39da9de1a66..bf5b4e0b4fd 100644 --- a/src/main/java/org/elasticsearch/index/mapper/DocumentMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/DocumentMapper.java @@ -28,6 +28,7 @@ import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.search.DocIdSet; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.elasticsearch.ElasticsearchGenerationException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; @@ -181,7 +182,7 @@ public class DocumentMapper implements ToXContent { private boolean hasNestedObjects = false; - private final Filter typeFilter; + private final Query typeFilter; private final Object mappersMutex = new Object(); @@ -199,7 +200,7 @@ public class DocumentMapper implements ToXContent { meta); this.documentParser = new DocumentParser(index, indexSettings, docMapperParser, this); - this.typeFilter = typeMapper().termFilter(type, null); + this.typeFilter = typeMapper().termQuery(type, null); if (rootMapper(ParentFieldMapper.class).active()) { // mark the routing field mapper as required @@ -313,7 +314,7 @@ public class DocumentMapper implements ToXContent { return rootMapper(SizeFieldMapper.class); } - public Filter typeFilter() { + public Query typeFilter() { return this.typeFilter; } diff --git a/src/main/java/org/elasticsearch/index/mapper/FieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/FieldMapper.java index 2c19d0e326c..67c14842032 100644 --- a/src/main/java/org/elasticsearch/index/mapper/FieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/FieldMapper.java @@ -245,26 +245,16 @@ public interface FieldMapper extends Mapper { Query termQuery(Object value, @Nullable QueryParseContext context); - Filter termFilter(Object value, @Nullable QueryParseContext context); - - Filter termsFilter(List values, @Nullable QueryParseContext context); - - Filter fieldDataTermsFilter(List values, @Nullable QueryParseContext context); + Query termsQuery(List values, @Nullable QueryParseContext context); Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context); - Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context); - Query fuzzyQuery(String value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions); Query prefixQuery(Object value, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryParseContext context); - Filter prefixFilter(Object value, @Nullable QueryParseContext context); - Query regexpQuery(Object value, int flags, int maxDeterminizedStates, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryParseContext context); - Filter regexpFilter(Object value, int flags, int maxDeterminizedStates, @Nullable QueryParseContext parseContext); - /** * A term query to use when parsing a query string. Can return null. */ @@ -275,7 +265,7 @@ public interface FieldMapper extends Mapper { * Null value filter, returns null if there is no null value associated with the field. */ @Nullable - Filter nullValueFilter(); + Query nullValueFilter(); FieldDataType fieldDataType(); diff --git a/src/main/java/org/elasticsearch/index/mapper/MapperService.java b/src/main/java/org/elasticsearch/index/mapper/MapperService.java index b2a82e39648..69584d9bfee 100755 --- a/src/main/java/org/elasticsearch/index/mapper/MapperService.java +++ b/src/main/java/org/elasticsearch/index/mapper/MapperService.java @@ -25,6 +25,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; + import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.DelegatingAnalyzerWrapper; import org.apache.lucene.index.IndexOptions; @@ -33,7 +34,7 @@ import org.apache.lucene.queries.TermsQuery; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; -import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.TermQuery; import org.apache.lucene.util.BytesRef; @@ -351,7 +352,7 @@ public class MapperService extends AbstractIndexComponent { * A filter for search. If a filter is required, will return it, otherwise, will return null. */ @Nullable - public Filter searchFilter(String... types) { + public Query searchFilter(String... types) { boolean filterPercolateType = hasMapping(PercolatorService.TYPE_NAME); if (types != null && filterPercolateType) { for (String type : types) { @@ -361,7 +362,7 @@ public class MapperService extends AbstractIndexComponent { } } } - Filter percolatorType = null; + Query percolatorType = null; if (filterPercolateType) { percolatorType = documentMapper(PercolatorService.TYPE_NAME).typeFilter(); } @@ -384,7 +385,7 @@ public class MapperService extends AbstractIndexComponent { // since they have different types (starting with __) if (types.length == 1) { DocumentMapper docMapper = documentMapper(types[0]); - Filter filter = docMapper != null ? docMapper.typeFilter() : new QueryWrapperFilter(new TermQuery(new Term(TypeFieldMapper.NAME, types[0]))); + Query filter = docMapper != null ? docMapper.typeFilter() : new TermQuery(new Term(TypeFieldMapper.NAME, types[0])); if (filterPercolateType) { BooleanQuery bq = new BooleanQuery(); bq.add(percolatorType, Occur.MUST_NOT); diff --git a/src/main/java/org/elasticsearch/index/mapper/core/AbstractFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/core/AbstractFieldMapper.java index 0a1bea01c95..425007219e3 100644 --- a/src/main/java/org/elasticsearch/index/mapper/core/AbstractFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/core/AbstractFieldMapper.java @@ -19,7 +19,6 @@ package org.elasticsearch.index.mapper.core; -import com.carrotsearch.hppc.ObjectOpenHashSet; import com.carrotsearch.hppc.cursors.ObjectCursor; import com.carrotsearch.hppc.cursors.ObjectObjectCursor; import com.google.common.base.Function; @@ -38,7 +37,6 @@ import org.apache.lucene.search.FuzzyQuery; import org.apache.lucene.search.MultiTermQuery; import org.apache.lucene.search.PrefixQuery; import org.apache.lucene.search.Query; -import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.RegexpQuery; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TermRangeQuery; @@ -65,7 +63,6 @@ import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.internal.AllFieldMapper; import org.elasticsearch.index.query.QueryParseContext; -import org.elasticsearch.index.search.FieldDataTermsFilter; import org.elasticsearch.index.similarity.SimilarityLookupService; import org.elasticsearch.index.similarity.SimilarityProvider; @@ -483,46 +480,26 @@ public abstract class AbstractFieldMapper implements FieldMapper { } @Override - public Filter termFilter(Object value, @Nullable QueryParseContext context) { - return new QueryWrapperFilter(new TermQuery(names().createIndexNameTerm(indexedValueForSearch(value)))); - } - - @Override - public Filter termsFilter(List values, @Nullable QueryParseContext context) { + public Query termsQuery(List values, @Nullable QueryParseContext context) { switch (values.size()) { case 0: - return Queries.newMatchNoDocsFilter(); + return Queries.newMatchNoDocsQuery(); case 1: // When there is a single term, it's important to return a term filter so that // it can return a DocIdSet that is directly backed by a postings list, instead // of loading everything into a bit set and returning an iterator based on the // bit set - return termFilter(values.get(0), context); + return termQuery(values.get(0), context); default: BytesRef[] bytesRefs = new BytesRef[values.size()]; for (int i = 0; i < bytesRefs.length; i++) { bytesRefs[i] = indexedValueForSearch(values.get(i)); } - return new QueryWrapperFilter(new TermsQuery(names.indexName(), bytesRefs)); + return new TermsQuery(names.indexName(), bytesRefs); } } - /** - * A terms filter based on the field data cache - */ - @Override - public Filter fieldDataTermsFilter(List values, @Nullable QueryParseContext context) { - // create with initial size large enough to avoid rehashing - ObjectOpenHashSet terms = - new ObjectOpenHashSet<>((int) (values.size() * (1 + ObjectOpenHashSet.DEFAULT_LOAD_FACTOR))); - for (int i = 0, len = values.size(); i < len; i++) { - terms.add(indexedValueForSearch(values.get(i))); - } - - return FieldDataTermsFilter.newBytes(context.getForField(this), terms); - } - @Override public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return new TermRangeQuery(names.indexName(), @@ -531,14 +508,6 @@ public abstract class AbstractFieldMapper implements FieldMapper { includeLower, includeUpper); } - @Override - public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return new QueryWrapperFilter(new TermRangeQuery(names.indexName(), - lowerTerm == null ? null : indexedValueForSearch(lowerTerm), - upperTerm == null ? null : indexedValueForSearch(upperTerm), - includeLower, includeUpper)); - } - @Override public Query fuzzyQuery(String value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions) { return new FuzzyQuery(names.createIndexNameTerm(indexedValueForSearch(value)), fuzziness.asDistance(value), prefixLength, maxExpansions, transpositions); @@ -553,11 +522,6 @@ public abstract class AbstractFieldMapper implements FieldMapper { return query; } - @Override - public Filter prefixFilter(Object value, @Nullable QueryParseContext context) { - return new QueryWrapperFilter(new PrefixQuery(names().createIndexNameTerm(indexedValueForSearch(value)))); - } - @Override public Query regexpQuery(Object value, int flags, int maxDeterminizedStates, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryParseContext context) { RegexpQuery query = new RegexpQuery(names().createIndexNameTerm(indexedValueForSearch(value)), flags, maxDeterminizedStates); @@ -568,12 +532,7 @@ public abstract class AbstractFieldMapper implements FieldMapper { } @Override - public Filter regexpFilter(Object value, int flags, int maxDeterminizedStates, @Nullable QueryParseContext parseContext) { - return new QueryWrapperFilter(new RegexpQuery(names().createIndexNameTerm(indexedValueForSearch(value)), flags, maxDeterminizedStates)); - } - - @Override - public Filter nullValueFilter() { + public Query nullValueFilter() { return null; } diff --git a/src/main/java/org/elasticsearch/index/mapper/core/ByteFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/core/ByteFieldMapper.java index 37a6f0a33b5..370a7a0d3a4 100644 --- a/src/main/java/org/elasticsearch/index/mapper/core/ByteFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/core/ByteFieldMapper.java @@ -42,14 +42,12 @@ import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.index.analysis.NumericIntegerAnalyzer; import org.elasticsearch.index.fielddata.FieldDataType; -import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeMappingException; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.query.QueryParseContext; -import org.elasticsearch.index.search.NumericRangeFieldDataFilter; import org.elasticsearch.index.similarity.SimilarityProvider; import java.io.IOException; @@ -209,23 +207,6 @@ public class ByteFieldMapper extends NumberFieldMapper { includeLower, includeUpper); } - @Override - public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, - @Nullable QueryParseContext context) { - return new QueryWrapperFilter(NumericRangeQuery.newIntRange(names.indexName(), precisionStep, - lowerTerm == null ? null : parseValueAsInt(lowerTerm), - upperTerm == null ? null : parseValueAsInt(upperTerm), - includeLower, includeUpper)); - } - - @Override - public Filter rangeFilter(QueryParseContext parseContext, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return NumericRangeFieldDataFilter.newByteRange((IndexNumericFieldData) parseContext.getForField(this), - lowerTerm == null ? null : parseValue(lowerTerm), - upperTerm == null ? null : parseValue(upperTerm), - includeLower, includeUpper); - } - @Override public Filter nullValueFilter() { if (nullValue == null) { diff --git a/src/main/java/org/elasticsearch/index/mapper/core/DateFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/core/DateFieldMapper.java index 5b8c5e8941f..cc7dd175a1e 100644 --- a/src/main/java/org/elasticsearch/index/mapper/core/DateFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/core/DateFieldMapper.java @@ -40,7 +40,6 @@ import org.elasticsearch.common.Strings; import org.elasticsearch.common.joda.DateMathParser; import org.elasticsearch.common.joda.FormatDateTimeFormatter; import org.elasticsearch.common.joda.Joda; -import org.elasticsearch.common.lucene.search.ResolvableFilter; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.common.util.LocaleUtils; @@ -48,15 +47,13 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.analysis.NumericDateAnalyzer; import org.elasticsearch.index.fielddata.FieldDataType; -import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeMappingException; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.core.LongFieldMapper.CustomLongNumericField; import org.elasticsearch.index.query.QueryParseContext; -import org.elasticsearch.index.search.NumericRangeFieldDataFilter; import org.elasticsearch.index.similarity.SimilarityProvider; import org.elasticsearch.search.internal.SearchContext; import org.joda.time.DateTimeZone; @@ -337,68 +334,6 @@ public class DateFieldMapper extends NumberFieldMapper { includeLower, includeUpper); } - @Override - public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return rangeFilter(lowerTerm, upperTerm, includeLower, includeUpper, null, null, context); - } - - public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable DateTimeZone timeZone, @Nullable DateMathParser forcedDateParser, @Nullable QueryParseContext context) { - return rangeFilter(null, lowerTerm, upperTerm, includeLower, includeUpper, timeZone, forcedDateParser, context); - } - - @Override - public Filter rangeFilter(QueryParseContext parseContext, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return rangeFilter(parseContext, lowerTerm, upperTerm, includeLower, includeUpper, null, null, context); - } - - /* - * `timeZone` parameter is only applied when: - * - not null - * - the object to parse is a String (does not apply to ms since epoch which are UTC based time values) - * - the String to parse does not have already a timezone defined (ie. `2014-01-01T00:00:00+03:00`) - */ - public Filter rangeFilter(QueryParseContext parseContext, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable DateTimeZone timeZone, @Nullable DateMathParser forcedDateParser, @Nullable QueryParseContext context) { - IndexNumericFieldData fieldData = parseContext != null ? (IndexNumericFieldData) parseContext.getForField(this) : null; - // If the current search context is null we're parsing percolator query or a index alias filter. - if (SearchContext.current() == null) { - return new LateParsingFilter(fieldData, lowerTerm, upperTerm, includeLower, includeUpper, timeZone, forcedDateParser); - } else { - return innerRangeFilter(fieldData, lowerTerm, upperTerm, includeLower, includeUpper, timeZone, forcedDateParser); - } - } - - private Filter innerRangeFilter(IndexNumericFieldData fieldData, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable DateTimeZone timeZone, @Nullable DateMathParser forcedDateParser) { - Long lowerVal = null; - Long upperVal = null; - if (lowerTerm != null) { - if (lowerTerm instanceof Number) { - lowerVal = ((Number) lowerTerm).longValue(); - } else { - String value = convertToString(lowerTerm); - lowerVal = parseToMilliseconds(value, false, timeZone, forcedDateParser); - } - } - if (upperTerm != null) { - if (upperTerm instanceof Number) { - upperVal = ((Number) upperTerm).longValue(); - } else { - String value = convertToString(upperTerm); - upperVal = parseToMilliseconds(value, includeUpper, timeZone, forcedDateParser); - } - } - - Filter filter; - if (fieldData != null) { - filter = NumericRangeFieldDataFilter.newLongRange(fieldData, lowerVal,upperVal, includeLower, includeUpper); - } else { - filter = new QueryWrapperFilter(NumericRangeQuery.newLongRange( - names.indexName(), precisionStep, lowerVal, upperVal, includeLower, includeUpper - )); - } - - return filter; - } - @Override public Filter nullValueFilter() { if (nullValue == null) { @@ -557,37 +492,6 @@ public class DateFieldMapper extends NumberFieldMapper { } } - private final class LateParsingFilter extends ResolvableFilter { - - final IndexNumericFieldData fieldData; - final Object lowerTerm; - final Object upperTerm; - final boolean includeLower; - final boolean includeUpper; - final DateTimeZone timeZone; - final DateMathParser forcedDateParser; - - public LateParsingFilter(IndexNumericFieldData fieldData, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, DateTimeZone timeZone, DateMathParser forcedDateParser) { - this.fieldData = fieldData; - this.lowerTerm = lowerTerm; - this.upperTerm = upperTerm; - this.includeLower = includeLower; - this.includeUpper = includeUpper; - this.timeZone = timeZone; - this.forcedDateParser = forcedDateParser; - } - - @Override - public Filter resolve() { - return innerRangeFilter(fieldData, lowerTerm, upperTerm, includeLower, includeUpper, timeZone, forcedDateParser); - } - - @Override - public String toString(String field) { - return "late(lower=" + lowerTerm + ",upper=" + upperTerm + ")"; - } - } - public final class LateParsingQuery extends Query { final Object lowerTerm; diff --git a/src/main/java/org/elasticsearch/index/mapper/core/DoubleFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/core/DoubleFieldMapper.java index e7ee19e3dba..6babe2e3a88 100644 --- a/src/main/java/org/elasticsearch/index/mapper/core/DoubleFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/core/DoubleFieldMapper.java @@ -47,14 +47,12 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.analysis.NumericDoubleAnalyzer; import org.elasticsearch.index.fielddata.FieldDataType; -import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeMappingException; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.query.QueryParseContext; -import org.elasticsearch.index.search.NumericRangeFieldDataFilter; import org.elasticsearch.index.similarity.SimilarityProvider; import java.io.IOException; @@ -200,26 +198,10 @@ public class DoubleFieldMapper extends NumberFieldMapper { includeLower, includeUpper); } - @Override - public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return new QueryWrapperFilter(NumericRangeQuery.newDoubleRange(names.indexName(), precisionStep, - lowerTerm == null ? null : parseDoubleValue(lowerTerm), - upperTerm == null ? null : parseDoubleValue(upperTerm), - includeLower, includeUpper)); - } - public Filter rangeFilter(Double lowerTerm, Double upperTerm, boolean includeLower, boolean includeUpper) { return new QueryWrapperFilter(NumericRangeQuery.newDoubleRange(names.indexName(), precisionStep, lowerTerm, upperTerm, includeLower, includeUpper)); } - @Override - public Filter rangeFilter(QueryParseContext parseContext, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return NumericRangeFieldDataFilter.newDoubleRange((IndexNumericFieldData) parseContext.getForField(this), - lowerTerm == null ? null : parseDoubleValue(lowerTerm), - upperTerm == null ? null : parseDoubleValue(upperTerm), - includeLower, includeUpper); - } - @Override public Filter nullValueFilter() { if (nullValue == null) { diff --git a/src/main/java/org/elasticsearch/index/mapper/core/FloatFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/core/FloatFieldMapper.java index 968261805d9..7595d168ceb 100644 --- a/src/main/java/org/elasticsearch/index/mapper/core/FloatFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/core/FloatFieldMapper.java @@ -48,14 +48,12 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.analysis.NumericFloatAnalyzer; import org.elasticsearch.index.fielddata.FieldDataType; -import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeMappingException; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.query.QueryParseContext; -import org.elasticsearch.index.search.NumericRangeFieldDataFilter; import org.elasticsearch.index.similarity.SimilarityProvider; import java.io.IOException; @@ -210,22 +208,6 @@ public class FloatFieldMapper extends NumberFieldMapper { includeLower, includeUpper); } - @Override - public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return new QueryWrapperFilter(NumericRangeQuery.newFloatRange(names.indexName(), precisionStep, - lowerTerm == null ? null : parseValue(lowerTerm), - upperTerm == null ? null : parseValue(upperTerm), - includeLower, includeUpper)); - } - - @Override - public Filter rangeFilter(QueryParseContext parseContext, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return NumericRangeFieldDataFilter.newFloatRange((IndexNumericFieldData) parseContext.getForField(this), - lowerTerm == null ? null : parseValue(lowerTerm), - upperTerm == null ? null : parseValue(upperTerm), - includeLower, includeUpper); - } - @Override public Filter nullValueFilter() { if (nullValue == null) { diff --git a/src/main/java/org/elasticsearch/index/mapper/core/IntegerFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/core/IntegerFieldMapper.java index 8fc32539120..78e3f7b5dfc 100644 --- a/src/main/java/org/elasticsearch/index/mapper/core/IntegerFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/core/IntegerFieldMapper.java @@ -43,14 +43,12 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.analysis.NumericIntegerAnalyzer; import org.elasticsearch.index.fielddata.FieldDataType; -import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeMappingException; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.query.QueryParseContext; -import org.elasticsearch.index.search.NumericRangeFieldDataFilter; import org.elasticsearch.index.similarity.SimilarityProvider; import java.io.IOException; @@ -204,22 +202,6 @@ public class IntegerFieldMapper extends NumberFieldMapper { includeLower, includeUpper); } - @Override - public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return new QueryWrapperFilter(NumericRangeQuery.newIntRange(names.indexName(), precisionStep, - lowerTerm == null ? null : parseValue(lowerTerm), - upperTerm == null ? null : parseValue(upperTerm), - includeLower, includeUpper)); - } - - @Override - public Filter rangeFilter(QueryParseContext parseContext, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return NumericRangeFieldDataFilter.newIntRange((IndexNumericFieldData) parseContext.getForField(this), - lowerTerm == null ? null : parseValue(lowerTerm), - upperTerm == null ? null : parseValue(upperTerm), - includeLower, includeUpper); - } - @Override public Filter nullValueFilter() { if (nullValue == null) { diff --git a/src/main/java/org/elasticsearch/index/mapper/core/LongFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/core/LongFieldMapper.java index bca94be2d34..bddb8466b43 100644 --- a/src/main/java/org/elasticsearch/index/mapper/core/LongFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/core/LongFieldMapper.java @@ -43,14 +43,12 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.analysis.NumericLongAnalyzer; import org.elasticsearch.index.fielddata.FieldDataType; -import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeMappingException; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.query.QueryParseContext; -import org.elasticsearch.index.search.NumericRangeFieldDataFilter; import org.elasticsearch.index.similarity.SimilarityProvider; import java.io.IOException; @@ -194,22 +192,6 @@ public class LongFieldMapper extends NumberFieldMapper { includeLower, includeUpper); } - @Override - public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return new QueryWrapperFilter(NumericRangeQuery.newLongRange(names.indexName(), precisionStep, - lowerTerm == null ? null : parseLongValue(lowerTerm), - upperTerm == null ? null : parseLongValue(upperTerm), - includeLower, includeUpper)); - } - - @Override - public Filter rangeFilter(QueryParseContext parseContext, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return NumericRangeFieldDataFilter.newLongRange((IndexNumericFieldData) parseContext.getForField(this), - lowerTerm == null ? null : parseLongValue(lowerTerm), - upperTerm == null ? null : parseLongValue(upperTerm), - includeLower, includeUpper); - } - @Override public Filter nullValueFilter() { if (nullValue == null) { diff --git a/src/main/java/org/elasticsearch/index/mapper/core/NumberFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/core/NumberFieldMapper.java index d042e1ea661..05f4044d142 100644 --- a/src/main/java/org/elasticsearch/index/mapper/core/NumberFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/core/NumberFieldMapper.java @@ -19,9 +19,7 @@ package org.elasticsearch.index.mapper.core; -import com.carrotsearch.hppc.DoubleOpenHashSet; import com.carrotsearch.hppc.LongArrayList; -import com.carrotsearch.hppc.LongOpenHashSet; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.NumericTokenStream; @@ -34,7 +32,6 @@ import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.IndexableFieldType; import org.apache.lucene.index.Term; -import org.apache.lucene.search.Filter; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.store.ByteArrayDataOutput; @@ -48,15 +45,13 @@ import org.elasticsearch.common.util.ByteUtils; import org.elasticsearch.common.util.CollectionUtils; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.analysis.NamedAnalyzer; -import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeMappingException; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.internal.AllFieldMapper; import org.elasticsearch.index.query.QueryParseContext; -import org.elasticsearch.index.search.FieldDataTermsFilter; import org.elasticsearch.index.similarity.SimilarityProvider; import java.io.IOException; @@ -277,55 +272,12 @@ public abstract class NumberFieldMapper extends AbstractFieldM return new TermQuery(new Term(names.indexName(), indexedValueForSearch(value))); } - @Override - public final Filter termFilter(Object value, @Nullable QueryParseContext context) { - // Made this method final because previously many subclasses duplicated - // the same code, returning a NumericRangeFilter, which should be less - // efficient than super's default impl of a single TermFilter. - return super.termFilter(value, context); - } - @Override public abstract Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context); - @Override - public abstract Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context); - @Override public abstract Query fuzzyQuery(String value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions); - /** - * A range filter based on the field data cache. - */ - public abstract Filter rangeFilter(QueryParseContext parseContext, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context); - - /** - * A terms filter based on the field data cache for numeric fields. - */ - @Override - public Filter fieldDataTermsFilter(List values, @Nullable QueryParseContext context) { - IndexNumericFieldData fieldData = context.getForField(this); - if (fieldData.getNumericType().isFloatingPoint()) { - // create with initial size large enough to avoid rehashing - DoubleOpenHashSet terms = - new DoubleOpenHashSet((int) (values.size() * (1 + DoubleOpenHashSet.DEFAULT_LOAD_FACTOR))); - for (int i = 0, len = values.size(); i < len; i++) { - terms.add(parseDoubleValue(values.get(i))); - } - - return FieldDataTermsFilter.newDoubles(fieldData, terms); - } else { - // create with initial size large enough to avoid rehashing - LongOpenHashSet terms = - new LongOpenHashSet((int) (values.size() * (1 + LongOpenHashSet.DEFAULT_LOAD_FACTOR))); - for (int i = 0, len = values.size(); i < len; i++) { - terms.add(parseLongValue(values.get(i))); - } - - return FieldDataTermsFilter.newLongs(fieldData, terms); - } - } - /** * Converts an object value into a double */ diff --git a/src/main/java/org/elasticsearch/index/mapper/core/ShortFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/core/ShortFieldMapper.java index a3a905aed99..fbaec8ad782 100644 --- a/src/main/java/org/elasticsearch/index/mapper/core/ShortFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/core/ShortFieldMapper.java @@ -44,14 +44,12 @@ import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.index.analysis.NumericIntegerAnalyzer; import org.elasticsearch.index.fielddata.FieldDataType; -import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeMappingException; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.query.QueryParseContext; -import org.elasticsearch.index.search.NumericRangeFieldDataFilter; import org.elasticsearch.index.similarity.SimilarityProvider; import java.io.IOException; @@ -210,22 +208,6 @@ public class ShortFieldMapper extends NumberFieldMapper { includeLower, includeUpper); } - @Override - public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return new QueryWrapperFilter(NumericRangeQuery.newIntRange(names.indexName(), precisionStep, - lowerTerm == null ? null : parseValueAsInt(lowerTerm), - upperTerm == null ? null : parseValueAsInt(upperTerm), - includeLower, includeUpper)); - } - - @Override - public Filter rangeFilter(QueryParseContext parseContext, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return new QueryWrapperFilter(NumericRangeFieldDataFilter.newShortRange((IndexNumericFieldData) parseContext.getForField(this), - lowerTerm == null ? null : parseValue(lowerTerm), - upperTerm == null ? null : parseValue(upperTerm), - includeLower, includeUpper)); - } - @Override public Filter nullValueFilter() { if (nullValue == null) { diff --git a/src/main/java/org/elasticsearch/index/mapper/core/StringFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/core/StringFieldMapper.java index d5c4812b17d..7c1e99ea663 100644 --- a/src/main/java/org/elasticsearch/index/mapper/core/StringFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/core/StringFieldMapper.java @@ -24,7 +24,7 @@ import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.SortedSetDocValuesField; import org.apache.lucene.index.IndexOptions; -import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; @@ -36,8 +36,8 @@ import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.index.fielddata.FieldDataType; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeMappingException; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.internal.AllFieldMapper; import org.elasticsearch.index.similarity.SimilarityProvider; @@ -275,11 +275,11 @@ public class StringFieldMapper extends AbstractFieldMapper implements Al } @Override - public Filter nullValueFilter() { + public Query nullValueFilter() { if (nullValue == null) { return null; } - return termFilter(nullValue, null); + return termQuery(nullValue, null); } @Override diff --git a/src/main/java/org/elasticsearch/index/mapper/internal/IdFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/internal/IdFieldMapper.java index c9a38f18f9c..870f2af5e96 100644 --- a/src/main/java/org/elasticsearch/index/mapper/internal/IdFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/internal/IdFieldMapper.java @@ -29,13 +29,11 @@ import org.apache.lucene.index.Term; import org.apache.lucene.queries.TermsQuery; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; -import org.apache.lucene.search.ConstantScoreQuery; -import org.apache.lucene.search.Filter; import org.apache.lucene.search.MultiTermQuery; import org.apache.lucene.search.PrefixQuery; import org.apache.lucene.search.Query; -import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.RegexpQuery; +import org.apache.lucene.search.TermQuery; import org.apache.lucene.util.BytesRef; import org.elasticsearch.Version; import org.elasticsearch.common.Nullable; @@ -49,8 +47,8 @@ import org.elasticsearch.index.fielddata.FieldDataType; import org.elasticsearch.index.mapper.InternalMapper; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeMappingException; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.RootMapper; import org.elasticsearch.index.mapper.Uid; @@ -59,6 +57,7 @@ import org.elasticsearch.index.query.QueryParseContext; import java.io.IOException; import java.util.Collection; +import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -191,24 +190,20 @@ public class IdFieldMapper extends AbstractFieldMapper implements Intern if (fieldType.indexOptions() != IndexOptions.NONE || context == null) { return super.termQuery(value, context); } - // no need for constant score filter, since we don't cache the filter, and it always takes deletes into account - return new ConstantScoreQuery(termFilter(value, context)); + final BytesRef[] uids = Uid.createTypeUids(context.queryTypes(), value); + if (uids.length == 1) { + return new TermQuery(new Term(UidFieldMapper.NAME, uids[0])); + } else { + return new TermsQuery(UidFieldMapper.NAME, uids); + } } @Override - public Filter termFilter(Object value, @Nullable QueryParseContext context) { + public Query termsQuery(List values, @Nullable QueryParseContext context) { if (fieldType.indexOptions() != IndexOptions.NONE || context == null) { - return super.termFilter(value, context); + return super.termsQuery(values, context); } - return new QueryWrapperFilter(new TermsQuery(UidFieldMapper.NAME, Uid.createTypeUids(context.queryTypes(), value))); - } - - @Override - public Filter termsFilter(List values, @Nullable QueryParseContext context) { - if (fieldType.indexOptions() != IndexOptions.NONE || context == null) { - return super.termsFilter(values, context); - } - return new QueryWrapperFilter(new TermsQuery(UidFieldMapper.NAME, Uid.createTypeUids(context.queryTypes(), values))); + return new TermsQuery(UidFieldMapper.NAME, Uid.createTypeUids(context.queryTypes(), values)); } @Override @@ -228,19 +223,6 @@ public class IdFieldMapper extends AbstractFieldMapper implements Intern return query; } - @Override - public Filter prefixFilter(Object value, @Nullable QueryParseContext context) { - if (fieldType.indexOptions() != IndexOptions.NONE || context == null) { - return super.prefixFilter(value, context); - } - Collection queryTypes = context.queryTypes(); - BooleanQuery filter = new BooleanQuery(); - for (String queryType : queryTypes) { - filter.add(new PrefixQuery(new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(queryType, BytesRefs.toBytesRef(value)))), BooleanClause.Occur.SHOULD); - } - return new QueryWrapperFilter(filter); - } - @Override public Query regexpQuery(Object value, int flags, int maxDeterminizedStates, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryParseContext context) { if (fieldType.indexOptions() != IndexOptions.NONE || context == null) { @@ -266,20 +248,6 @@ public class IdFieldMapper extends AbstractFieldMapper implements Intern return query; } - @Override - public Filter regexpFilter(Object value, int flags, int maxDeterminizedStates, @Nullable QueryParseContext context) { - if (fieldType.indexOptions() != IndexOptions.NONE || context == null) { - return super.regexpFilter(value, flags, maxDeterminizedStates, context); - } - Collection queryTypes = context.queryTypes(); - BooleanQuery filter = new BooleanQuery(); - for (String queryType : queryTypes) { - filter.add(new RegexpQuery(new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(queryType, BytesRefs.toBytesRef(value))), - flags, maxDeterminizedStates), BooleanClause.Occur.SHOULD); - } - return new QueryWrapperFilter(filter); - } - @Override public void preParse(ParseContext context) throws IOException { if (context.sourceToParse().id() != null) { diff --git a/src/main/java/org/elasticsearch/index/mapper/internal/ParentFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/internal/ParentFieldMapper.java index d6a14f7be3c..0657aaa76bd 100644 --- a/src/main/java/org/elasticsearch/index/mapper/internal/ParentFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/internal/ParentFieldMapper.java @@ -23,20 +23,14 @@ import com.google.common.base.Objects; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.index.IndexOptions; -import org.apache.lucene.index.Term; import org.apache.lucene.queries.TermsQuery; -import org.apache.lucene.search.ConstantScoreQuery; -import org.apache.lucene.search.Filter; import org.apache.lucene.search.Query; -import org.apache.lucene.search.QueryWrapperFilter; -import org.apache.lucene.search.TermQuery; import org.apache.lucene.util.BytesRef; import org.elasticsearch.Version; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.lucene.BytesRefs; import org.elasticsearch.common.lucene.Lucene; -import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.loader.SettingsLoader; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -45,8 +39,8 @@ import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.InternalMapper; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeMappingException; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.RootMapper; import org.elasticsearch.index.mapper.Uid; @@ -55,6 +49,7 @@ import org.elasticsearch.index.query.QueryParseContext; import java.io.IOException; import java.util.ArrayList; +import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -263,51 +258,13 @@ public class ParentFieldMapper extends AbstractFieldMapper implements Inter @Override public Query termQuery(Object value, @Nullable QueryParseContext context) { - if (context == null) { - return super.termQuery(value, context); - } - return new ConstantScoreQuery(termFilter(value, context)); + return termsQuery(Collections.singletonList(value), context); } @Override - public Filter termFilter(Object value, @Nullable QueryParseContext context) { + public Query termsQuery(List values, @Nullable QueryParseContext context) { if (context == null) { - return super.termFilter(value, context); - } - BytesRef bValue = BytesRefs.toBytesRef(value); - if (Uid.hasDelimiter(bValue)) { - return new QueryWrapperFilter(new TermQuery(new Term(names.indexName(), bValue))); - } - - List types = new ArrayList<>(context.mapperService().types().size()); - for (DocumentMapper documentMapper : context.mapperService().docMappers(false)) { - if (!documentMapper.parentFieldMapper().active()) { - types.add(documentMapper.type()); - } - } - - if (types.isEmpty()) { - return Queries.newMatchNoDocsFilter(); - } else if (types.size() == 1) { - return new QueryWrapperFilter(new TermQuery(new Term(names.indexName(), Uid.createUidAsBytes(types.get(0), bValue)))); - } else { - // we use all non child types, cause we don't know if its exact or not... - List typesValues = new ArrayList<>(types.size()); - for (String type : context.mapperService().types()) { - typesValues.add(Uid.createUidAsBytes(type, bValue)); - } - return new QueryWrapperFilter(new TermsQuery(names.indexName(), typesValues)); - } - } - - @Override - public Filter termsFilter(List values, @Nullable QueryParseContext context) { - if (context == null) { - return super.termsFilter(values, context); - } - // This will not be invoked if values is empty, so don't check for empty - if (values.size() == 1) { - return termFilter(values.get(0), context); + return super.termsQuery(values, context); } List types = new ArrayList<>(context.mapperService().types().size()); @@ -329,7 +286,7 @@ public class ParentFieldMapper extends AbstractFieldMapper implements Inter } } } - return new QueryWrapperFilter(new TermsQuery(names.indexName(), bValues)); + return new TermsQuery(names.indexName(), bValues); } /** diff --git a/src/main/java/org/elasticsearch/index/mapper/internal/TypeFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/internal/TypeFieldMapper.java index b5668761c03..d51d56530a3 100644 --- a/src/main/java/org/elasticsearch/index/mapper/internal/TypeFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/internal/TypeFieldMapper.java @@ -25,10 +25,8 @@ import org.apache.lucene.document.SortedSetDocValuesField; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.Term; import org.apache.lucene.search.ConstantScoreQuery; -import org.apache.lucene.search.Filter; import org.apache.lucene.search.PrefixQuery; import org.apache.lucene.search.Query; -import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.TermQuery; import org.apache.lucene.util.BytesRef; import org.elasticsearch.Version; @@ -41,8 +39,8 @@ import org.elasticsearch.index.fielddata.FieldDataType; import org.elasticsearch.index.mapper.InternalMapper; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeMappingException; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.RootMapper; import org.elasticsearch.index.mapper.Uid; @@ -133,15 +131,10 @@ public class TypeFieldMapper extends AbstractFieldMapper implements Inte @Override public Query termQuery(Object value, @Nullable QueryParseContext context) { - return new ConstantScoreQuery(termFilter(value, context)); - } - - @Override - public Filter termFilter(Object value, @Nullable QueryParseContext context) { if (fieldType.indexOptions() == IndexOptions.NONE) { - return new QueryWrapperFilter(new PrefixQuery(new Term(UidFieldMapper.NAME, Uid.typePrefixAsBytes(BytesRefs.toBytesRef(value))))); + return new ConstantScoreQuery(new PrefixQuery(new Term(UidFieldMapper.NAME, Uid.typePrefixAsBytes(BytesRefs.toBytesRef(value))))); } - return new QueryWrapperFilter(new TermQuery(names().createIndexNameTerm(BytesRefs.toBytesRef(value)))); + return new ConstantScoreQuery(new TermQuery(names().createIndexNameTerm(BytesRefs.toBytesRef(value)))); } @Override diff --git a/src/main/java/org/elasticsearch/index/mapper/ip/IpFieldMapper.java b/src/main/java/org/elasticsearch/index/mapper/ip/IpFieldMapper.java index 64ba3bace25..a6e176790d1 100644 --- a/src/main/java/org/elasticsearch/index/mapper/ip/IpFieldMapper.java +++ b/src/main/java/org/elasticsearch/index/mapper/ip/IpFieldMapper.java @@ -44,16 +44,14 @@ import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.index.analysis.NumericAnalyzer; import org.elasticsearch.index.analysis.NumericTokenizer; import org.elasticsearch.index.fielddata.FieldDataType; -import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeMappingException; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.core.LongFieldMapper.CustomLongNumericField; import org.elasticsearch.index.mapper.core.NumberFieldMapper; import org.elasticsearch.index.query.QueryParseContext; -import org.elasticsearch.index.search.NumericRangeFieldDataFilter; import org.elasticsearch.index.similarity.SimilarityProvider; import java.io.IOException; @@ -251,22 +249,6 @@ public class IpFieldMapper extends NumberFieldMapper { includeLower, includeUpper); } - @Override - public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return new QueryWrapperFilter(NumericRangeQuery.newLongRange(names.indexName(), precisionStep, - lowerTerm == null ? null : parseValue(lowerTerm), - upperTerm == null ? null : parseValue(upperTerm), - includeLower, includeUpper)); - } - - @Override - public Filter rangeFilter(QueryParseContext parseContext, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { - return NumericRangeFieldDataFilter.newLongRange((IndexNumericFieldData) parseContext.getForField(this), - lowerTerm == null ? null : parseValue(lowerTerm), - upperTerm == null ? null : parseValue(upperTerm), - includeLower, includeUpper); - } - @Override public Filter nullValueFilter() { if (nullValue == null) { diff --git a/src/main/java/org/elasticsearch/index/query/AndFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/AndQueryBuilder.java similarity index 72% rename from src/main/java/org/elasticsearch/index/query/AndFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/AndQueryBuilder.java index 87611a03b73..8acd58774ef 100644 --- a/src/main/java/org/elasticsearch/index/query/AndFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/AndQueryBuilder.java @@ -27,17 +27,17 @@ import java.util.ArrayList; /** * A filter that matches documents matching boolean combinations of other filters. - * @deprecated Use {@link BoolFilterBuilder} instead + * @deprecated Use {@link BoolQueryBuilder} instead */ @Deprecated -public class AndFilterBuilder extends BaseFilterBuilder { +public class AndQueryBuilder extends BaseQueryBuilder { - private ArrayList filters = Lists.newArrayList(); + private ArrayList filters = Lists.newArrayList(); - private String filterName; + private String queryName; - public AndFilterBuilder(FilterBuilder... filters) { - for (FilterBuilder filter : filters) { + public AndQueryBuilder(QueryBuilder... filters) { + for (QueryBuilder filter : filters) { this.filters.add(filter); } } @@ -45,7 +45,7 @@ public class AndFilterBuilder extends BaseFilterBuilder { /** * Adds a filter to the list of filters to "and". */ - public AndFilterBuilder add(FilterBuilder filterBuilder) { + public AndQueryBuilder add(QueryBuilder filterBuilder) { filters.add(filterBuilder); return this; } @@ -53,21 +53,21 @@ public class AndFilterBuilder extends BaseFilterBuilder { /** * Sets the filter name for the filter that can be used when searching for matched_filters per hit. */ - public AndFilterBuilder filterName(String filterName) { - this.filterName = filterName; + public AndQueryBuilder queryName(String queryName) { + this.queryName = queryName; return this; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(AndFilterParser.NAME); + builder.startObject(AndQueryParser.NAME); builder.startArray("filters"); - for (FilterBuilder filter : filters) { + for (QueryBuilder filter : filters) { filter.toXContent(builder, params); } builder.endArray(); - if (filterName != null) { - builder.field("_name", filterName); + if (queryName != null) { + builder.field("_name", queryName); } builder.endObject(); } diff --git a/src/main/java/org/elasticsearch/index/query/AndFilterParser.java b/src/main/java/org/elasticsearch/index/query/AndQueryParser.java similarity index 67% rename from src/main/java/org/elasticsearch/index/query/AndFilterParser.java rename to src/main/java/org/elasticsearch/index/query/AndQueryParser.java index f0c8c2724bb..8c1969de561 100644 --- a/src/main/java/org/elasticsearch/index/query/AndFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/AndQueryParser.java @@ -21,8 +21,7 @@ package org.elasticsearch.index.query; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.QueryWrapperFilter; +import org.apache.lucene.search.Query; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentParser; @@ -34,12 +33,13 @@ import static com.google.common.collect.Lists.newArrayList; /** * */ -public class AndFilterParser implements FilterParser { +@Deprecated +public class AndQueryParser implements QueryParser { public static final String NAME = "and"; @Inject - public AndFilterParser() { + public AndQueryParser() { } @Override @@ -48,21 +48,21 @@ public class AndFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); - ArrayList filters = newArrayList(); - boolean filtersFound = false; + ArrayList queries = newArrayList(); + boolean queriesFound = false; - String filterName = null; + String queryName = null; String currentFieldName = null; XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.START_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - filtersFound = true; - Filter filter = parseContext.parseInnerFilter(); + queriesFound = true; + Query filter = parseContext.parseInnerFilter(); if (filter != null) { - filters.add(filter); + queries.add(filter); } } } else { @@ -73,50 +73,48 @@ public class AndFilterParser implements FilterParser { // skip } else if (token == XContentParser.Token.START_ARRAY) { if ("filters".equals(currentFieldName)) { - filtersFound = true; + queriesFound = true; while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - Filter filter = parseContext.parseInnerFilter(); + Query filter = parseContext.parseInnerFilter(); if (filter != null) { - filters.add(filter); + queries.add(filter); } } } else { - filtersFound = true; + queriesFound = true; while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - Filter filter = parseContext.parseInnerFilter(); + Query filter = parseContext.parseInnerFilter(); if (filter != null) { - filters.add(filter); + queries.add(filter); } } } } else if (token.isValue()) { if ("_name".equals(currentFieldName)) { - filterName = parser.text(); + queryName = parser.text(); } else { - throw new QueryParsingException(parseContext, "[and] filter does not support [" + currentFieldName + "]"); + throw new QueryParsingException(parseContext, "[and] query does not support [" + currentFieldName + "]"); } } } } - if (!filtersFound) { - throw new QueryParsingException(parseContext, "[and] filter requires 'filters' to be set on it'"); + if (!queriesFound) { + throw new QueryParsingException(parseContext, "[and] query requires 'filters' to be set on it'"); } - if (filters.isEmpty()) { + if (queries.isEmpty()) { // no filters provided, this should be ignored upstream return null; } - // no need to cache this one - BooleanQuery boolQuery = new BooleanQuery(); - for (Filter filter : filters) { - boolQuery.add(filter, Occur.MUST); + BooleanQuery query = new BooleanQuery(); + for (Query f : queries) { + query.add(f, Occur.MUST); } - Filter filter = new QueryWrapperFilter(boolQuery); - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); + if (queryName != null) { + parseContext.addNamedQuery(queryName, query); } - return filter; + return query; } } \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/BaseFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/BaseFilterBuilder.java deleted file mode 100644 index 69264fb4b45..00000000000 --- a/src/main/java/org/elasticsearch/index/query/BaseFilterBuilder.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.ElasticsearchException; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.common.xcontent.XContentType; - -import java.io.IOException; - -/** - * - */ -public abstract class BaseFilterBuilder implements FilterBuilder { - - @Override - public String toString() { - try { - XContentBuilder builder = XContentFactory.jsonBuilder(); - builder.prettyPrint(); - toXContent(builder, EMPTY_PARAMS); - return builder.string(); - } catch (Exception e) { - throw new ElasticsearchException("Failed to build filter", e); - } - } - - @Override - public BytesReference buildAsBytes() { - return buildAsBytes(XContentType.JSON); - } - - @Override - public BytesReference buildAsBytes(XContentType contentType) { - try { - XContentBuilder builder = XContentFactory.contentBuilder(contentType); - toXContent(builder, EMPTY_PARAMS); - return builder.bytes(); - } catch (Exception e) { - throw new ElasticsearchException("Failed to build filter", e); - } - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - doXContent(builder, params); - builder.endObject(); - return builder; - } - - protected abstract void doXContent(XContentBuilder builder, Params params) throws IOException; -} diff --git a/src/main/java/org/elasticsearch/index/query/BoolFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/BoolFilterBuilder.java deleted file mode 100644 index 330adaf8d08..00000000000 --- a/src/main/java/org/elasticsearch/index/query/BoolFilterBuilder.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.common.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * A filter that matches documents matching boolean combinations of other filters. - */ -public class BoolFilterBuilder extends BaseFilterBuilder { - - private ArrayList mustClauses = new ArrayList<>(); - - private ArrayList mustNotClauses = new ArrayList<>(); - - private ArrayList shouldClauses = new ArrayList<>(); - - private String filterName; - - /** - * Adds a filter that must appear in the matching documents. - */ - public BoolFilterBuilder must(FilterBuilder filterBuilder) { - mustClauses.add(filterBuilder); - return this; - } - - /** - * Adds a filter that must not appear in the matching documents. - */ - public BoolFilterBuilder mustNot(FilterBuilder filterBuilder) { - mustNotClauses.add(filterBuilder); - return this; - } - - - /** - * Adds a filter that should appear in the matching documents. For a boolean filter - * with no MUST clauses one or more SHOULD clauses must match a document - * for the BooleanQuery to match. - */ - public BoolFilterBuilder should(FilterBuilder filterBuilder) { - shouldClauses.add(filterBuilder); - return this; - } - - /** - * Adds multiple must filters. - */ - public BoolFilterBuilder must(FilterBuilder... filterBuilders) { - for (FilterBuilder fb : filterBuilders) { - mustClauses.add(fb); - } - return this; - } - - /** - * Adds multiple must not filters. - */ - public BoolFilterBuilder mustNot(FilterBuilder... filterBuilders) { - for (FilterBuilder fb : filterBuilders) { - mustNotClauses.add(fb); - } - return this; - } - - /** - * Adds multiple should filters. - */ - public BoolFilterBuilder should(FilterBuilder... filterBuilders) { - for (FilterBuilder fb : filterBuilders) { - shouldClauses.add(fb); - } - return this; - } - - /** - * Returns true iff this filter builder has at least one should, must or mustNot clause. - * Otherwise false. - */ - public boolean hasClauses() { - return !(mustClauses.isEmpty() && shouldClauses.isEmpty() && mustNotClauses.isEmpty()); - } - - /** - * Sets the filter name for the filter that can be used when searching for matched_filters per hit. - */ - public BoolFilterBuilder filterName(String filterName) { - this.filterName = filterName; - return this; - } - - @Override - protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject("bool"); - doXArrayContent("must", mustClauses, builder, params); - doXArrayContent("must_not", mustNotClauses, builder, params); - doXArrayContent("should", shouldClauses, builder, params); - - if (filterName != null) { - builder.field("_name", filterName); - } - builder.endObject(); - } - - private void doXArrayContent(String field, List clauses, XContentBuilder builder, Params params) throws IOException { - if (clauses.isEmpty()) { - return; - } - if (clauses.size() == 1) { - builder.field(field); - clauses.get(0).toXContent(builder, params); - } else { - builder.startArray(field); - for (FilterBuilder clause : clauses) { - clause.toXContent(builder, params); - } - builder.endArray(); - } - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/BoolFilterParser.java b/src/main/java/org/elasticsearch/index/query/BoolFilterParser.java deleted file mode 100644 index 7d96f1bc3bc..00000000000 --- a/src/main/java/org/elasticsearch/index/query/BoolFilterParser.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.apache.lucene.search.BooleanClause; -import org.apache.lucene.search.BooleanQuery; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.QueryWrapperFilter; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.xcontent.XContentParser; - -import java.io.IOException; - -/** - * - */ -public class BoolFilterParser implements FilterParser { - - public static final String NAME = "bool"; - - @Inject - public BoolFilterParser() { - } - - @Override - public String[] names() { - return new String[]{NAME}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - BooleanQuery boolFilter = new BooleanQuery(); - - String filterName = null; - String currentFieldName = null; - XContentParser.Token token; - - boolean hasAnyFilter = false; - - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (parseContext.isDeprecatedSetting(currentFieldName)) { - // skip - } else if (token == XContentParser.Token.START_OBJECT) { - if ("must".equals(currentFieldName)) { - hasAnyFilter = true; - Filter filter = parseContext.parseInnerFilter(); - if (filter != null) { - boolFilter.add(new BooleanClause(filter, BooleanClause.Occur.FILTER)); - } - } else if ("must_not".equals(currentFieldName) || "mustNot".equals(currentFieldName)) { - hasAnyFilter = true; - Filter filter = parseContext.parseInnerFilter(); - if (filter != null) { - boolFilter.add(new BooleanClause(filter, BooleanClause.Occur.MUST_NOT)); - } - } else if ("should".equals(currentFieldName)) { - hasAnyFilter = true; - Filter filter = parseContext.parseInnerFilter(); - if (filter != null) { - boolFilter.setMinimumNumberShouldMatch(1); - boolFilter.add(new BooleanClause(filter, BooleanClause.Occur.SHOULD)); - } - } else { - throw new QueryParsingException(parseContext, "[bool] filter does not support [" + currentFieldName + "]"); - } - } else if (token == XContentParser.Token.START_ARRAY) { - if ("must".equals(currentFieldName)) { - hasAnyFilter = true; - while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - Filter filter = parseContext.parseInnerFilter(); - if (filter != null) { - boolFilter.add(new BooleanClause(filter, BooleanClause.Occur.MUST)); - } - } - } else if ("must_not".equals(currentFieldName) || "mustNot".equals(currentFieldName)) { - hasAnyFilter = true; - while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - Filter filter = parseContext.parseInnerFilter(); - if (filter != null) { - boolFilter.add(new BooleanClause(filter, BooleanClause.Occur.MUST_NOT)); - } - } - } else if ("should".equals(currentFieldName)) { - hasAnyFilter = true; - while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - Filter filter = parseContext.parseInnerFilter(); - if (filter != null) { - boolFilter.setMinimumNumberShouldMatch(1); - boolFilter.add(new BooleanClause(filter, BooleanClause.Occur.SHOULD)); - } - } - } else { - throw new QueryParsingException(parseContext, "[bool] filter does not support [" + currentFieldName + "]"); - } - } else if (token.isValue()) { - if ("_name".equals(currentFieldName)) { - filterName = parser.text(); - } else { - throw new QueryParsingException(parseContext, "[bool] filter does not support [" + currentFieldName + "]"); - } - } - } - - if (!hasAnyFilter) { - throw new QueryParsingException(parseContext, "[bool] filter has no inner should/must/must_not elements"); - } - - if (boolFilter.clauses().isEmpty()) { - // no filters provided, it should be ignored upstream - return null; - } - - Filter filter = new QueryWrapperFilter(boolFilter); - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); - } - return filter; - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/BoolQueryParser.java b/src/main/java/org/elasticsearch/index/query/BoolQueryParser.java index b7c31647c94..6f64586afdb 100644 --- a/src/main/java/org/elasticsearch/index/query/BoolQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/BoolQueryParser.java @@ -68,6 +68,8 @@ public class BoolQueryParser implements QueryParser { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); + } else if (parseContext.isDeprecatedSetting(currentFieldName)) { + // skip } else if (token == XContentParser.Token.START_OBJECT) { if ("must".equals(currentFieldName)) { Query query = parseContext.parseInnerQuery(); @@ -80,9 +82,12 @@ public class BoolQueryParser implements QueryParser { clauses.add(new BooleanClause(query, BooleanClause.Occur.MUST_NOT)); } } else if ("should".equals(currentFieldName)) { - Query query = parseContext.parseInnerQuery(); + Query query = parseContext.parseInnerFilter(); if (query != null) { clauses.add(new BooleanClause(query, BooleanClause.Occur.SHOULD)); + if (parseContext.isFilter() && minimumShouldMatch == null) { + minimumShouldMatch = "1"; + } } } else { throw new QueryParsingException(parseContext, "[bool] query does not support [" + currentFieldName + "]"); @@ -107,6 +112,9 @@ public class BoolQueryParser implements QueryParser { Query query = parseContext.parseInnerQuery(); if (query != null) { clauses.add(new BooleanClause(query, BooleanClause.Occur.SHOULD)); + if (parseContext.isFilter() && minimumShouldMatch == null) { + minimumShouldMatch = "1"; + } } } } else { diff --git a/src/main/java/org/elasticsearch/index/query/BytesFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/BytesQueryBuilder.java similarity index 87% rename from src/main/java/org/elasticsearch/index/query/BytesFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/BytesQueryBuilder.java index a86ea239f70..6c4cc7c875f 100644 --- a/src/main/java/org/elasticsearch/index/query/BytesFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/BytesQueryBuilder.java @@ -25,14 +25,14 @@ import org.elasticsearch.common.xcontent.*; import java.io.IOException; /** - * FilterBuilder that constructs filters from {@link org.elasticsearch.common.bytes.BytesReference} + * QueryBuilder that constructs queries from {@link org.elasticsearch.common.bytes.BytesReference} * source */ -public class BytesFilterBuilder extends BaseFilterBuilder { +public class BytesQueryBuilder extends BaseQueryBuilder { private final BytesReference source; - public BytesFilterBuilder(BytesReference source) { + public BytesQueryBuilder(BytesReference source) { this.source = source; } diff --git a/src/main/java/org/elasticsearch/index/query/ConstantScoreQueryBuilder.java b/src/main/java/org/elasticsearch/index/query/ConstantScoreQueryBuilder.java index ac85e61fb98..5ad250dde97 100644 --- a/src/main/java/org/elasticsearch/index/query/ConstantScoreQueryBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/ConstantScoreQueryBuilder.java @@ -22,6 +22,7 @@ package org.elasticsearch.index.query; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; +import java.util.Objects; /** * A query that wraps a filter and simply returns a constant score equal to the @@ -31,32 +32,19 @@ import java.io.IOException; */ public class ConstantScoreQueryBuilder extends BaseQueryBuilder implements BoostableQueryBuilder { - private final FilterBuilder filterBuilder; - private final QueryBuilder queryBuilder; + private final QueryBuilder filterBuilder; private float boost = -1; - - /** - * A query that wraps a filter and simply returns a constant score equal to the - * query boost for every document in the filter. - * - * @param filterBuilder The filter to wrap in a constant score query - */ - public ConstantScoreQueryBuilder(FilterBuilder filterBuilder) { - this.filterBuilder = filterBuilder; - this.queryBuilder = null; - } /** * A query that wraps a query and simply returns a constant score equal to the * query boost for every document in the query. * - * @param queryBuilder The query to wrap in a constant score query + * @param filterBuilder The query to wrap in a constant score query */ - public ConstantScoreQueryBuilder(QueryBuilder queryBuilder) { - this.filterBuilder = null; - this.queryBuilder = queryBuilder; - } + public ConstantScoreQueryBuilder(QueryBuilder filterBuilder) { + this.filterBuilder = Objects.requireNonNull(filterBuilder); + } /** * Sets the boost for this query. Documents matching this query will (in addition to the normal @@ -71,15 +59,9 @@ public class ConstantScoreQueryBuilder extends BaseQueryBuilder implements Boost @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(ConstantScoreQueryParser.NAME); - if (queryBuilder != null) { - assert filterBuilder == null; - builder.field("query"); - queryBuilder.toXContent(builder, params); - } else { - builder.field("filter"); - filterBuilder.toXContent(builder, params); - } - + builder.field("filter"); + filterBuilder.toXContent(builder, params); + if (boost != -1) { builder.field("boost", boost); } diff --git a/src/main/java/org/elasticsearch/index/query/ConstantScoreQueryParser.java b/src/main/java/org/elasticsearch/index/query/ConstantScoreQueryParser.java index 593643abc52..e1941d849c4 100644 --- a/src/main/java/org/elasticsearch/index/query/ConstantScoreQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/ConstantScoreQueryParser.java @@ -20,8 +20,8 @@ package org.elasticsearch.index.query; import org.apache.lucene.search.ConstantScoreQuery; -import org.apache.lucene.search.Filter; import org.apache.lucene.search.Query; +import org.elasticsearch.common.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentParser; @@ -34,6 +34,7 @@ import java.io.IOException; public class ConstantScoreQueryParser implements QueryParser { public static final String NAME = "constant_score"; + private static final ParseField INNER_QUERY_FIELD = new ParseField("filter", "query"); @Inject public ConstantScoreQueryParser() { @@ -48,9 +49,7 @@ public class ConstantScoreQueryParser implements QueryParser { public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); - Filter filter = null; - boolean filterFound = false; - Query query = null; + Query filter = null; boolean queryFound = false; float boost = 1.0f; @@ -62,11 +61,8 @@ public class ConstantScoreQueryParser implements QueryParser { } else if (parseContext.isDeprecatedSetting(currentFieldName)) { // skip } else if (token == XContentParser.Token.START_OBJECT) { - if ("filter".equals(currentFieldName)) { + if (INNER_QUERY_FIELD.match(currentFieldName)) { filter = parseContext.parseInnerFilter(); - filterFound = true; - } else if ("query".equals(currentFieldName)) { - query = parseContext.parseInnerQuery(); queryFound = true; } else { throw new QueryParsingException(parseContext, "[constant_score] query does not support [" + currentFieldName + "]"); @@ -79,22 +75,16 @@ public class ConstantScoreQueryParser implements QueryParser { } } } - if (!filterFound && !queryFound) { - throw new QueryParsingException(parseContext, "[constant_score] requires either 'filter' or 'query' element"); + if (!queryFound) { + throw new QueryParsingException(parseContext, "[constant_score] requires a 'filter' element"); } - if (query == null && filter == null) { + if (filter == null) { return null; } - if (filter != null) { - Query query1 = new ConstantScoreQuery(filter); - query1.setBoost(boost); - return query1; - } - // Query - query = new ConstantScoreQuery(query); - query.setBoost(boost); - return query; + filter = new ConstantScoreQuery(filter); + filter.setBoost(boost); + return filter; } } \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/ExistsFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/ExistsQueryBuilder.java similarity index 68% rename from src/main/java/org/elasticsearch/index/query/ExistsFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/ExistsQueryBuilder.java index 56511c4223b..7613ce56515 100644 --- a/src/main/java/org/elasticsearch/index/query/ExistsFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/ExistsQueryBuilder.java @@ -24,35 +24,32 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; /** - * Constructs a filter that only match on documents that the field has a value in them. - * - * + * Constructs a query that only match on documents that the field has a value in them. */ -public class ExistsFilterBuilder extends BaseFilterBuilder { +public class ExistsQueryBuilder extends BaseQueryBuilder { private String name; - private String filterName; + private String queryName; - public ExistsFilterBuilder(String name) { + public ExistsQueryBuilder(String name) { this.name = name; } /** - * Sets the filter name for the filter that can be used when searching for matched_filters per hit. + * Sets the query name for the query that can be used when searching for matched_queries per hit. */ - public ExistsFilterBuilder filterName(String filterName) { - this.filterName = filterName; + public ExistsQueryBuilder queryName(String queryName) { + this.queryName = queryName; return this; } - @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(ExistsFilterParser.NAME); + builder.startObject(ExistsQueryParser.NAME); builder.field("field", name); - if (filterName != null) { - builder.field("_name", filterName); + if (queryName != null) { + builder.field("_name", queryName); } builder.endObject(); } diff --git a/src/main/java/org/elasticsearch/index/query/ExistsFilterParser.java b/src/main/java/org/elasticsearch/index/query/ExistsQueryParser.java similarity index 79% rename from src/main/java/org/elasticsearch/index/query/ExistsFilterParser.java rename to src/main/java/org/elasticsearch/index/query/ExistsQueryParser.java index 8dc0a3eb2c1..b77fa8f1da6 100644 --- a/src/main/java/org/elasticsearch/index/query/ExistsFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/ExistsQueryParser.java @@ -21,12 +21,10 @@ package org.elasticsearch.index.query; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; -import org.apache.lucene.search.Filter; +import org.apache.lucene.search.ConstantScoreQuery; import org.apache.lucene.search.Query; -import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.TermRangeQuery; import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.lucene.HashedBytesRef; import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.mapper.FieldMappers; @@ -39,12 +37,12 @@ import java.util.List; /** * */ -public class ExistsFilterParser implements FilterParser { +public class ExistsQueryParser implements QueryParser { public static final String NAME = "exists"; @Inject - public ExistsFilterParser() { + public ExistsQueryParser() { } @Override @@ -53,11 +51,11 @@ public class ExistsFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); String fieldPattern = null; - String filterName = null; + String queryName = null; XContentParser.Token token; String currentFieldName = null; @@ -68,9 +66,9 @@ public class ExistsFilterParser implements FilterParser { if ("field".equals(currentFieldName)) { fieldPattern = parser.text(); } else if ("_name".equals(currentFieldName)) { - filterName = parser.text(); + queryName = parser.text(); } else { - throw new QueryParsingException(parseContext, "[exists] filter does not support [" + currentFieldName + "]"); + throw new QueryParsingException(parseContext, "[exists] query does not support [" + currentFieldName + "]"); } } } @@ -79,10 +77,10 @@ public class ExistsFilterParser implements FilterParser { throw new QueryParsingException(parseContext, "exists must be provided with a [field]"); } - return newFilter(parseContext, fieldPattern, filterName); + return newFilter(parseContext, fieldPattern, queryName); } - public static Filter newFilter(QueryParseContext parseContext, String fieldPattern, String filterName) { + public static Query newFilter(QueryParseContext parseContext, String fieldPattern, String queryName) { final FieldMappers fieldNamesMappers = parseContext.mapperService().fullName(FieldNamesFieldMapper.NAME); final FieldNamesFieldMapper fieldNamesMapper = (FieldNamesFieldMapper)fieldNamesMappers.mapper(); @@ -95,7 +93,7 @@ public class ExistsFilterParser implements FilterParser { List fields = parseContext.simpleMatchToIndexNames(fieldPattern); if (fields.isEmpty()) { // no fields exists, so we should not match anything - return Queries.newMatchNoDocsFilter(); + return Queries.newMatchNoDocsQuery(); } BooleanQuery boolFilter = new BooleanQuery(); @@ -109,11 +107,11 @@ public class ExistsFilterParser implements FilterParser { } else { f = field; } - filter = fieldNamesMapper.termFilter(f, parseContext); + filter = fieldNamesMapper.termQuery(f, parseContext); } // if _field_names are not indexed, we need to go the slow way if (filter == null && smartNameFieldMappers != null && smartNameFieldMappers.hasMapper()) { - filter = smartNameFieldMappers.mapper().rangeFilter(null, null, true, true, parseContext); + filter = smartNameFieldMappers.mapper().rangeQuery(null, null, true, true, parseContext); } if (filter == null) { filter = new TermRangeQuery(field, null, null, true, true); @@ -121,11 +119,10 @@ public class ExistsFilterParser implements FilterParser { boolFilter.add(filter, BooleanClause.Occur.SHOULD); } - Filter filter = new QueryWrapperFilter(boolFilter); - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); + if (queryName != null) { + parseContext.addNamedQuery(queryName, boolFilter); } - return filter; + return new ConstantScoreQuery(boolFilter); } } diff --git a/src/main/java/org/elasticsearch/index/query/FQueryFilterParser.java b/src/main/java/org/elasticsearch/index/query/FQueryFilterParser.java index b349dd3e65c..4c0f782efe2 100644 --- a/src/main/java/org/elasticsearch/index/query/FQueryFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/FQueryFilterParser.java @@ -19,9 +19,8 @@ package org.elasticsearch.index.query; -import org.apache.lucene.search.Filter; +import org.apache.lucene.search.ConstantScoreQuery; import org.apache.lucene.search.Query; -import org.apache.lucene.search.QueryWrapperFilter; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentParser; @@ -31,7 +30,8 @@ import java.io.IOException; * The "fquery" filter is the same as the {@link QueryFilterParser} except that it allows also to * associate a name with the query filter. */ -public class FQueryFilterParser implements FilterParser { +@Deprecated +public class FQueryFilterParser implements QueryParser { public static final String NAME = "fquery"; @@ -45,13 +45,13 @@ public class FQueryFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); Query query = null; boolean queryFound = false; - String filterName = null; + String queryName = null; String currentFieldName = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { @@ -64,13 +64,13 @@ public class FQueryFilterParser implements FilterParser { queryFound = true; query = parseContext.parseInnerQuery(); } else { - throw new QueryParsingException(parseContext, "[fquery] filter does not support [" + currentFieldName + "]"); + throw new QueryParsingException(parseContext, "[fquery] query does not support [" + currentFieldName + "]"); } } else if (token.isValue()) { if ("_name".equals(currentFieldName)) { - filterName = parser.text(); + queryName = parser.text(); } else { - throw new QueryParsingException(parseContext, "[fquery] filter does not support [" + currentFieldName + "]"); + throw new QueryParsingException(parseContext, "[fquery] query does not support [" + currentFieldName + "]"); } } } @@ -80,10 +80,10 @@ public class FQueryFilterParser implements FilterParser { if (query == null) { return null; } - Filter filter = new QueryWrapperFilter(query); - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); + query = new ConstantScoreQuery(query); + if (queryName != null) { + parseContext.addNamedQuery(queryName, query); } - return filter; + return query; } } diff --git a/src/main/java/org/elasticsearch/index/query/FilterBuilder.java b/src/main/java/org/elasticsearch/index/query/FilterBuilder.java deleted file mode 100644 index 77eb4d136ca..00000000000 --- a/src/main/java/org/elasticsearch/index/query/FilterBuilder.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.xcontent.ToXContent; -import org.elasticsearch.common.xcontent.XContentType; - -/** - * - */ -public interface FilterBuilder extends ToXContent { - - BytesReference buildAsBytes(); - - BytesReference buildAsBytes(XContentType contentType); - -} diff --git a/src/main/java/org/elasticsearch/index/query/FilterBuilders.java b/src/main/java/org/elasticsearch/index/query/FilterBuilders.java deleted file mode 100644 index 3cd63fb6e51..00000000000 --- a/src/main/java/org/elasticsearch/index/query/FilterBuilders.java +++ /dev/null @@ -1,571 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.action.search.SearchRequestBuilder; -import org.elasticsearch.common.Nullable; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.geo.GeoPoint; -import org.elasticsearch.common.geo.ShapeRelation; -import org.elasticsearch.common.geo.builders.ShapeBuilder; - -/** - * A static factory for simple "import static" usage. - */ -public abstract class FilterBuilders { - - /** - * A filter that matches all documents. - */ - public static MatchAllFilterBuilder matchAllFilter() { - return new MatchAllFilterBuilder(); - } - - /** - * A filter that limits the results to the provided limit value (per shard!). - * @deprecated Use {@link SearchRequestBuilder#setTerminateAfter(int)} instead. - */ - @Deprecated - public static LimitFilterBuilder limitFilter(int limit) { - return new LimitFilterBuilder(limit); - } - - public static NestedFilterBuilder nestedFilter(String path, QueryBuilder query) { - return new NestedFilterBuilder(path, query); - } - - public static NestedFilterBuilder nestedFilter(String path, FilterBuilder filter) { - return new NestedFilterBuilder(path, filter); - } - - /** - * Creates a new ids filter with the provided doc/mapping types. - * - * @param types The types to match the ids against. - */ - public static IdsFilterBuilder idsFilter(@Nullable String... types) { - return new IdsFilterBuilder(types); - } - - /** - * A filter based on doc/mapping type. - */ - public static TypeFilterBuilder typeFilter(String type) { - return new TypeFilterBuilder(type); - } - - /** - * A filter for a field based on a term. - * - * @param name The field name - * @param value The term value - */ - public static TermFilterBuilder termFilter(String name, String value) { - return new TermFilterBuilder(name, value); - } - - /** - * A filter for a field based on a term. - * - * @param name The field name - * @param value The term value - */ - public static TermFilterBuilder termFilter(String name, int value) { - return new TermFilterBuilder(name, value); - } - - /** - * A filter for a field based on a term. - * - * @param name The field name - * @param value The term value - */ - public static TermFilterBuilder termFilter(String name, long value) { - return new TermFilterBuilder(name, value); - } - - /** - * A filter for a field based on a term. - * - * @param name The field name - * @param value The term value - */ - public static TermFilterBuilder termFilter(String name, float value) { - return new TermFilterBuilder(name, value); - } - - /** - * A filter for a field based on a term. - * - * @param name The field name - * @param value The term value - */ - public static TermFilterBuilder termFilter(String name, double value) { - return new TermFilterBuilder(name, value); - } - - /** - * A filter for a field based on a term. - * - * @param name The field name - * @param value The term value - */ - public static TermFilterBuilder termFilter(String name, Object value) { - return new TermFilterBuilder(name, value); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public static TermsFilterBuilder termsFilter(String name, String... values) { - return new TermsFilterBuilder(name, values); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public static TermsFilterBuilder termsFilter(String name, int... values) { - return new TermsFilterBuilder(name, values); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public static TermsFilterBuilder termsFilter(String name, long... values) { - return new TermsFilterBuilder(name, values); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public static TermsFilterBuilder termsFilter(String name, float... values) { - return new TermsFilterBuilder(name, values); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public static TermsFilterBuilder termsFilter(String name, double... values) { - return new TermsFilterBuilder(name, values); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public static TermsFilterBuilder termsFilter(String name, Object... values) { - return new TermsFilterBuilder(name, values); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public static TermsFilterBuilder termsFilter(String name, Iterable values) { - return new TermsFilterBuilder(name, values); - } - - /** - * A terms lookup filter for the provided field name. A lookup terms filter can - * extract the terms to filter by from another doc in an index. - */ - public static TermsLookupFilterBuilder termsLookupFilter(String name) { - return new TermsLookupFilterBuilder(name); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public static TermsFilterBuilder inFilter(String name, String... values) { - return new TermsFilterBuilder(name, values); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public static TermsFilterBuilder inFilter(String name, int... values) { - return new TermsFilterBuilder(name, values); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public static TermsFilterBuilder inFilter(String name, long... values) { - return new TermsFilterBuilder(name, values); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public static TermsFilterBuilder inFilter(String name, float... values) { - return new TermsFilterBuilder(name, values); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public static TermsFilterBuilder inFilter(String name, double... values) { - return new TermsFilterBuilder(name, values); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public static TermsFilterBuilder inFilter(String name, Object... values) { - return new TermsFilterBuilder(name, values); - } - - /** - * A filter that restricts search results to values that have a matching prefix in a given - * field. - * - * @param name The field name - * @param prefix The prefix - */ - public static PrefixFilterBuilder prefixFilter(String name, String prefix) { - return new PrefixFilterBuilder(name, prefix); - } - - /** - * A filter that restricts search results to field values that match a given regular expression. - * - * @param name The field name - * @param regexp The regular expression - */ - public static RegexpFilterBuilder regexpFilter(String name, String regexp) { - return new RegexpFilterBuilder(name, regexp); - } - - /** - * A filter that restricts search results to values that are within the given range. - * - * @param name The field name - */ - public static RangeFilterBuilder rangeFilter(String name) { - return new RangeFilterBuilder(name); - } - - /** - * A filter that simply wraps a query. - * - * @param queryBuilder The query to wrap as a filter - */ - public static QueryFilterBuilder queryFilter(QueryBuilder queryBuilder) { - return new QueryFilterBuilder(queryBuilder); - } - - /** - * A builder for filter based on a script. - * - * @param script The script to filter by. - */ - public static ScriptFilterBuilder scriptFilter(String script) { - return new ScriptFilterBuilder(script); - } - - /** - * A filter to filter based on a specific distance from a specific geo location / point. - * - * @param name The location field name. - */ - public static GeoDistanceFilterBuilder geoDistanceFilter(String name) { - return new GeoDistanceFilterBuilder(name); - } - - /** - * A filter to filter based on a specific range from a specific geo location / point. - * - * @param name The location field name. - */ - public static GeoDistanceRangeFilterBuilder geoDistanceRangeFilter(String name) { - return new GeoDistanceRangeFilterBuilder(name); - } - - /** - * A filter to filter based on a bounding box defined by top left and bottom right locations / points - * - * @param name The location field name. - */ - public static GeoBoundingBoxFilterBuilder geoBoundingBoxFilter(String name) { - return new GeoBoundingBoxFilterBuilder(name); - } - - /** - * A filter based on a bounding box defined by geohash. The field this filter is applied to - * must have {"type":"geo_point", "geohash":true} - * to work. - * - * @param name The geo point field name. - */ - public static GeohashCellFilter.Builder geoHashCellFilter(String name) { - return new GeohashCellFilter.Builder(name); - } - - /** - * A filter based on a bounding box defined by geohash. The field this filter is applied to - * must have {"type":"geo_point", "geohash":true} - * to work. - * - * @param name The geo point field name. - * @param geohash The Geohash to filter - */ - public static GeohashCellFilter.Builder geoHashCellFilter(String name, String geohash) { - return new GeohashCellFilter.Builder(name, geohash); - } - - /** - * A filter based on a bounding box defined by geohash. The field this filter is applied to - * must have {"type":"geo_point", "geohash":true} - * to work. - * - * @param name The geo point field name. - * @param point a geo point within the geohash bucket - */ - public static GeohashCellFilter.Builder geoHashCellFilter(String name, GeoPoint point) { - return new GeohashCellFilter.Builder(name, point); - } - - /** - * A filter based on a bounding box defined by geohash. The field this filter is applied to - * must have {"type":"geo_point", "geohash":true} - * to work. - * - * @param name The geo point field name - * @param geohash The Geohash to filter - * @param neighbors should the neighbor cell also be filtered - */ - public static GeohashCellFilter.Builder geoHashCellFilter(String name, String geohash, boolean neighbors) { - return new GeohashCellFilter.Builder(name, geohash, neighbors); - } - - /** - * A filter to filter based on a polygon defined by a set of locations / points. - * - * @param name The location field name. - */ - public static GeoPolygonFilterBuilder geoPolygonFilter(String name) { - return new GeoPolygonFilterBuilder(name); - } - - /** - * A filter based on the relationship of a shape and indexed shapes - * - * @param name The shape field name - * @param shape Shape to use in the filter - * @param relation relation of the shapes - */ - public static GeoShapeFilterBuilder geoShapeFilter(String name, ShapeBuilder shape, ShapeRelation relation) { - return new GeoShapeFilterBuilder(name, shape, relation); - } - - public static GeoShapeFilterBuilder geoShapeFilter(String name, String indexedShapeId, String indexedShapeType, ShapeRelation relation) { - return new GeoShapeFilterBuilder(name, indexedShapeId, indexedShapeType, relation); - } - - /** - * A filter to filter indexed shapes intersecting with shapes - * - * @param name The shape field name - * @param shape Shape to use in the filter - */ - public static GeoShapeFilterBuilder geoIntersectionFilter(String name, ShapeBuilder shape) { - return geoShapeFilter(name, shape, ShapeRelation.INTERSECTS); - } - - public static GeoShapeFilterBuilder geoIntersectionFilter(String name, String indexedShapeId, String indexedShapeType) { - return geoShapeFilter(name, indexedShapeId, indexedShapeType, ShapeRelation.INTERSECTS); - } - - /** - * A filter to filter indexed shapes that are contained by a shape - * - * @param name The shape field name - * @param shape Shape to use in the filter - */ - public static GeoShapeFilterBuilder geoWithinFilter(String name, ShapeBuilder shape) { - return geoShapeFilter(name, shape, ShapeRelation.WITHIN); - } - - public static GeoShapeFilterBuilder geoWithinFilter(String name, String indexedShapeId, String indexedShapeType) { - return geoShapeFilter(name, indexedShapeId, indexedShapeType, ShapeRelation.WITHIN); - } - - /** - * A filter to filter indexed shapes that are not intersection with the query shape - * - * @param name The shape field name - * @param shape Shape to use in the filter - */ - public static GeoShapeFilterBuilder geoDisjointFilter(String name, ShapeBuilder shape) { - return geoShapeFilter(name, shape, ShapeRelation.DISJOINT); - } - - public static GeoShapeFilterBuilder geoDisjointFilter(String name, String indexedShapeId, String indexedShapeType) { - return geoShapeFilter(name, indexedShapeId, indexedShapeType, ShapeRelation.DISJOINT); - } - - /** - * A filter to filter only documents where a field exists in them. - * - * @param name The name of the field - */ - public static ExistsFilterBuilder existsFilter(String name) { - return new ExistsFilterBuilder(name); - } - - /** - * A filter to filter only documents where a field does not exists in them. - * - * @param name The name of the field - */ - public static MissingFilterBuilder missingFilter(String name) { - return new MissingFilterBuilder(name); - } - - /** - * Constructs a child filter, with the child type and the query to run against child documents, with - * the result of the filter being the *parent* documents. - * - * @param type The child type - * @param query The query to run against the child type - */ - public static HasChildFilterBuilder hasChildFilter(String type, QueryBuilder query) { - return new HasChildFilterBuilder(type, query); - } - - /** - * Constructs a child filter, with the child type and the filter to run against child documents, with - * the result of the filter being the *parent* documents. - * - * @param type The child type - * @param filter The query to run against the child type - */ - public static HasChildFilterBuilder hasChildFilter(String type, FilterBuilder filter) { - return new HasChildFilterBuilder(type, filter); - } - - /** - * Constructs a parent filter, with the parent type and the query to run against parent documents, with - * the result of the filter being the *child* documents. - * - * @param parentType The parent type - * @param query The query to run against the parent type - */ - public static HasParentFilterBuilder hasParentFilter(String parentType, QueryBuilder query) { - return new HasParentFilterBuilder(parentType, query); - } - - /** - * Constructs a parent filter, with the parent type and the filter to run against parent documents, with - * the result of the filter being the *child* documents. - * - * @param parentType The parent type - * @param filter The filter to run against the parent type - */ - public static HasParentFilterBuilder hasParentFilter(String parentType, FilterBuilder filter) { - return new HasParentFilterBuilder(parentType, filter); - } - - public static BoolFilterBuilder boolFilter() { - return new BoolFilterBuilder(); - } - - /** - * @deprecated Use {@link #boolFilter()} instead - */ - @Deprecated - public static AndFilterBuilder andFilter(FilterBuilder... filters) { - return new AndFilterBuilder(filters); - } - - /** - * @deprecated Use {@link #boolFilter()} instead - */ - @Deprecated - public static OrFilterBuilder orFilter(FilterBuilder... filters) { - return new OrFilterBuilder(filters); - } - - public static NotFilterBuilder notFilter(FilterBuilder filter) { - return new NotFilterBuilder(filter); - } - - public static IndicesFilterBuilder indicesFilter(FilterBuilder filter, String... indices) { - return new IndicesFilterBuilder(filter, indices); - } - - public static WrapperFilterBuilder wrapperFilter(String filter) { - return new WrapperFilterBuilder(filter); - } - - public static WrapperFilterBuilder wrapperFilter(byte[] data, int offset, int length) { - return new WrapperFilterBuilder(data, offset, length); - } - - /** - * Constructs a bytes filter to generate a filter from a {@link BytesReference} source - * - * @param source The filter source - */ - public static BytesFilterBuilder bytesFilter(BytesReference source) { - return new BytesFilterBuilder(source); - } - - private FilterBuilders() { - - } -} diff --git a/src/main/java/org/elasticsearch/index/query/FilterParser.java b/src/main/java/org/elasticsearch/index/query/FilterParser.java deleted file mode 100644 index 260f8284b7e..00000000000 --- a/src/main/java/org/elasticsearch/index/query/FilterParser.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.apache.lucene.search.Filter; -import org.elasticsearch.common.Nullable; - -import java.io.IOException; - -/** - * - */ -public interface FilterParser { - - /** - * The names this filter is registered under. - */ - String[] names(); - - /** - * Parses the into a filter from the current parser location. Will be at "START_OBJECT" location, - * and should end when the token is at the matching "END_OBJECT". - *

- * The parser should return null value when it should be ignored, regardless under which context - * it is. For example, an and filter with "and []" (no clauses), should be ignored regardless if - * it exists within a must clause or a must_not bool clause (that is why returning MATCH_ALL will - * not be good, since it will not match anything when returned within a must_not clause). - */ - @Nullable - Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException; -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/FilterParserFactory.java b/src/main/java/org/elasticsearch/index/query/FilterParserFactory.java deleted file mode 100644 index 900951edcf8..00000000000 --- a/src/main/java/org/elasticsearch/index/query/FilterParserFactory.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.common.settings.Settings; - -/** - * - */ -public interface FilterParserFactory { - - FilterParser create(String name, Settings settings); -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/FilteredQueryBuilder.java b/src/main/java/org/elasticsearch/index/query/FilteredQueryBuilder.java index 400a1850167..e9c9e960787 100644 --- a/src/main/java/org/elasticsearch/index/query/FilteredQueryBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/FilteredQueryBuilder.java @@ -31,7 +31,7 @@ public class FilteredQueryBuilder extends BaseQueryBuilder implements BoostableQ private final QueryBuilder queryBuilder; - private final FilterBuilder filterBuilder; + private final QueryBuilder filterBuilder; private float boost = -1; @@ -43,7 +43,7 @@ public class FilteredQueryBuilder extends BaseQueryBuilder implements BoostableQ * @param queryBuilder The query to apply the filter to (Can be null) * @param filterBuilder The filter to apply on the query (Can be null) */ - public FilteredQueryBuilder(@Nullable QueryBuilder queryBuilder, @Nullable FilterBuilder filterBuilder) { + public FilteredQueryBuilder(@Nullable QueryBuilder queryBuilder, @Nullable QueryBuilder filterBuilder) { this.queryBuilder = queryBuilder; this.filterBuilder = filterBuilder; } diff --git a/src/main/java/org/elasticsearch/index/query/FilteredQueryParser.java b/src/main/java/org/elasticsearch/index/query/FilteredQueryParser.java index 9e2f8e133b3..68f270be58e 100644 --- a/src/main/java/org/elasticsearch/index/query/FilteredQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/FilteredQueryParser.java @@ -23,6 +23,7 @@ import org.apache.lucene.search.ConstantScoreQuery; import org.apache.lucene.search.Filter; import org.apache.lucene.search.FilteredQuery; import org.apache.lucene.search.Query; +import org.apache.lucene.search.QueryWrapperFilter; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.xcontent.XContentParser; @@ -50,7 +51,7 @@ public class FilteredQueryParser implements QueryParser { XContentParser parser = parseContext.parser(); Query query = Queries.newMatchAllQuery(); - Filter filter = null; + Query filter = null; boolean filterFound = false; float boost = 1.0f; String queryName = null; @@ -130,7 +131,10 @@ public class FilteredQueryParser implements QueryParser { return q; } - FilteredQuery filteredQuery = new FilteredQuery(query, filter, filterStrategy); + if (filter instanceof Filter == false) { + filter = new QueryWrapperFilter(filter); + } + FilteredQuery filteredQuery = new FilteredQuery(query, (Filter) filter, filterStrategy); filteredQuery.setBoost(boost); if (queryName != null) { parseContext.addNamedQuery(queryName, filteredQuery); diff --git a/src/main/java/org/elasticsearch/index/query/FuzzyQueryParser.java b/src/main/java/org/elasticsearch/index/query/FuzzyQueryParser.java index 229fcc95c72..de6fdd00cde 100644 --- a/src/main/java/org/elasticsearch/index/query/FuzzyQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/FuzzyQueryParser.java @@ -22,6 +22,7 @@ package org.elasticsearch.index.query; import org.apache.lucene.index.Term; import org.apache.lucene.search.FuzzyQuery; import org.apache.lucene.search.MultiTermQuery; +import org.apache.lucene.search.MultiTermQuery.RewriteMethod; import org.apache.lucene.search.Query; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.inject.Inject; @@ -69,6 +70,9 @@ public class FuzzyQueryParser implements QueryParser { boolean transpositions = false; String queryName = null; MultiTermQuery.RewriteMethod rewriteMethod = null; + if (parseContext.isFilter()) { + rewriteMethod = MultiTermQuery.CONSTANT_SCORE_REWRITE; + } token = parser.nextToken(); if (token == XContentParser.Token.START_OBJECT) { String currentFieldName = null; diff --git a/src/main/java/org/elasticsearch/index/query/GeoBoundingBoxFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/GeoBoundingBoxQueryBuilder.java similarity index 73% rename from src/main/java/org/elasticsearch/index/query/GeoBoundingBoxFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/GeoBoundingBoxQueryBuilder.java index 40b41c7ffbd..66f2ba5bcd2 100644 --- a/src/main/java/org/elasticsearch/index/query/GeoBoundingBoxFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/GeoBoundingBoxQueryBuilder.java @@ -28,10 +28,10 @@ import java.io.IOException; /** * */ -public class GeoBoundingBoxFilterBuilder extends BaseFilterBuilder { +public class GeoBoundingBoxQueryBuilder extends BaseQueryBuilder { - public static final String TOP_LEFT = GeoBoundingBoxFilterParser.TOP_LEFT; - public static final String BOTTOM_RIGHT = GeoBoundingBoxFilterParser.BOTTOM_RIGHT; + public static final String TOP_LEFT = GeoBoundingBoxQueryParser.TOP_LEFT; + public static final String BOTTOM_RIGHT = GeoBoundingBoxQueryParser.BOTTOM_RIGHT; private static final int TOP = 0; private static final int LEFT = 1; @@ -42,10 +42,10 @@ public class GeoBoundingBoxFilterBuilder extends BaseFilterBuilder { private double[] box = {Double.NaN, Double.NaN, Double.NaN, Double.NaN}; - private String filterName; + private String queryName; private String type; - public GeoBoundingBoxFilterBuilder(String name) { + public GeoBoundingBoxQueryBuilder(String name) { this.name = name; } @@ -55,17 +55,17 @@ public class GeoBoundingBoxFilterBuilder extends BaseFilterBuilder { * @param lat The latitude * @param lon The longitude */ - public GeoBoundingBoxFilterBuilder topLeft(double lat, double lon) { + public GeoBoundingBoxQueryBuilder topLeft(double lat, double lon) { box[TOP] = lat; box[LEFT] = lon; return this; } - public GeoBoundingBoxFilterBuilder topLeft(GeoPoint point) { + public GeoBoundingBoxQueryBuilder topLeft(GeoPoint point) { return topLeft(point.lat(), point.lon()); } - public GeoBoundingBoxFilterBuilder topLeft(String geohash) { + public GeoBoundingBoxQueryBuilder topLeft(String geohash) { return topLeft(GeoHashUtils.decode(geohash)); } @@ -75,17 +75,17 @@ public class GeoBoundingBoxFilterBuilder extends BaseFilterBuilder { * @param lat The latitude * @param lon The longitude */ - public GeoBoundingBoxFilterBuilder bottomRight(double lat, double lon) { + public GeoBoundingBoxQueryBuilder bottomRight(double lat, double lon) { box[BOTTOM] = lat; box[RIGHT] = lon; return this; } - public GeoBoundingBoxFilterBuilder bottomRight(GeoPoint point) { + public GeoBoundingBoxQueryBuilder bottomRight(GeoPoint point) { return bottomRight(point.lat(), point.lon()); } - public GeoBoundingBoxFilterBuilder bottomRight(String geohash) { + public GeoBoundingBoxQueryBuilder bottomRight(String geohash) { return bottomRight(GeoHashUtils.decode(geohash)); } @@ -95,17 +95,17 @@ public class GeoBoundingBoxFilterBuilder extends BaseFilterBuilder { * @param lat The latitude * @param lon The longitude */ - public GeoBoundingBoxFilterBuilder bottomLeft(double lat, double lon) { + public GeoBoundingBoxQueryBuilder bottomLeft(double lat, double lon) { box[BOTTOM] = lat; box[LEFT] = lon; return this; } - public GeoBoundingBoxFilterBuilder bottomLeft(GeoPoint point) { + public GeoBoundingBoxQueryBuilder bottomLeft(GeoPoint point) { return bottomLeft(point.lat(), point.lon()); } - public GeoBoundingBoxFilterBuilder bottomLeft(String geohash) { + public GeoBoundingBoxQueryBuilder bottomLeft(String geohash) { return bottomLeft(GeoHashUtils.decode(geohash)); } @@ -115,25 +115,25 @@ public class GeoBoundingBoxFilterBuilder extends BaseFilterBuilder { * @param lat The latitude * @param lon The longitude */ - public GeoBoundingBoxFilterBuilder topRight(double lat, double lon) { + public GeoBoundingBoxQueryBuilder topRight(double lat, double lon) { box[TOP] = lat; box[RIGHT] = lon; return this; } - public GeoBoundingBoxFilterBuilder topRight(GeoPoint point) { + public GeoBoundingBoxQueryBuilder topRight(GeoPoint point) { return topRight(point.lat(), point.lon()); } - public GeoBoundingBoxFilterBuilder topRight(String geohash) { + public GeoBoundingBoxQueryBuilder topRight(String geohash) { return topRight(GeoHashUtils.decode(geohash)); } /** * Sets the filter name for the filter that can be used when searching for matched_filters per hit. */ - public GeoBoundingBoxFilterBuilder filterName(String filterName) { - this.filterName = filterName; + public GeoBoundingBoxQueryBuilder queryName(String queryName) { + this.queryName = queryName; return this; } @@ -141,7 +141,7 @@ public class GeoBoundingBoxFilterBuilder extends BaseFilterBuilder { * Sets the type of executing of the geo bounding box. Can be either `memory` or `indexed`. Defaults * to `memory`. */ - public GeoBoundingBoxFilterBuilder type(String type) { + public GeoBoundingBoxQueryBuilder type(String type) { this.type = type; return this; } @@ -159,15 +159,15 @@ public class GeoBoundingBoxFilterBuilder extends BaseFilterBuilder { throw new IllegalArgumentException("geo_bounding_box requires left longitude to be set"); } - builder.startObject(GeoBoundingBoxFilterParser.NAME); + builder.startObject(GeoBoundingBoxQueryParser.NAME); builder.startObject(name); builder.array(TOP_LEFT, box[LEFT], box[TOP]); builder.array(BOTTOM_RIGHT, box[RIGHT], box[BOTTOM]); builder.endObject(); - if (filterName != null) { - builder.field("_name", filterName); + if (queryName != null) { + builder.field("_name", queryName); } if (type != null) { builder.field("type", type); diff --git a/src/main/java/org/elasticsearch/index/query/GeoBoundingBoxFilterParser.java b/src/main/java/org/elasticsearch/index/query/GeoBoundingBoxQueryParser.java similarity index 94% rename from src/main/java/org/elasticsearch/index/query/GeoBoundingBoxFilterParser.java rename to src/main/java/org/elasticsearch/index/query/GeoBoundingBoxQueryParser.java index 6441b8d4b07..875bad4e95a 100644 --- a/src/main/java/org/elasticsearch/index/query/GeoBoundingBoxFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/GeoBoundingBoxQueryParser.java @@ -19,7 +19,7 @@ package org.elasticsearch.index.query; -import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.geo.GeoUtils; @@ -37,7 +37,7 @@ import java.io.IOException; /** * */ -public class GeoBoundingBoxFilterParser implements FilterParser { +public class GeoBoundingBoxQueryParser implements QueryParser { public static final String TOP = "top"; public static final String LEFT = "left"; @@ -58,7 +58,7 @@ public class GeoBoundingBoxFilterParser implements FilterParser { public static final String FIELD = "field"; @Inject - public GeoBoundingBoxFilterParser() { + public GeoBoundingBoxQueryParser() { } @Override @@ -67,7 +67,7 @@ public class GeoBoundingBoxFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); String fieldName = null; @@ -77,7 +77,7 @@ public class GeoBoundingBoxFilterParser implements FilterParser { double left = Double.NaN; double right = Double.NaN; - String filterName = null; + String queryName = null; String currentFieldName = null; XContentParser.Token token; boolean normalize = true; @@ -135,13 +135,13 @@ public class GeoBoundingBoxFilterParser implements FilterParser { } } else if (token.isValue()) { if ("_name".equals(currentFieldName)) { - filterName = parser.text(); + queryName = parser.text(); } else if ("normalize".equals(currentFieldName)) { normalize = parser.booleanValue(); } else if ("type".equals(currentFieldName)) { type = parser.text(); } else { - throw new QueryParsingException(parseContext, "[geo_bbox] filter does not support [" + currentFieldName + "]"); + throw new QueryParsingException(parseContext, "[geo_bbox] query does not support [" + currentFieldName + "]"); } } } @@ -171,7 +171,7 @@ public class GeoBoundingBoxFilterParser implements FilterParser { } GeoPointFieldMapper geoMapper = ((GeoPointFieldMapper) mapper); - Filter filter; + Query filter; if ("indexed".equals(type)) { filter = IndexedGeoBoundingBoxFilter.create(topLeft, bottomRight, geoMapper); } else if ("memory".equals(type)) { @@ -182,8 +182,8 @@ public class GeoBoundingBoxFilterParser implements FilterParser { + "] not supported, either 'indexed' or 'memory' are allowed"); } - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); + if (queryName != null) { + parseContext.addNamedQuery(queryName, filter); } return filter; } diff --git a/src/main/java/org/elasticsearch/index/query/GeoDistanceFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/GeoDistanceQueryBuilder.java similarity index 73% rename from src/main/java/org/elasticsearch/index/query/GeoDistanceFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/GeoDistanceQueryBuilder.java index a45aee92c6c..2ea4e92a567 100644 --- a/src/main/java/org/elasticsearch/index/query/GeoDistanceFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/GeoDistanceQueryBuilder.java @@ -29,7 +29,7 @@ import java.util.Locale; /** * */ -public class GeoDistanceFilterBuilder extends BaseFilterBuilder { +public class GeoDistanceQueryBuilder extends BaseQueryBuilder { private final String name; @@ -45,49 +45,49 @@ public class GeoDistanceFilterBuilder extends BaseFilterBuilder { private String optimizeBbox; - private String filterName; + private String queryName; - public GeoDistanceFilterBuilder(String name) { + public GeoDistanceQueryBuilder(String name) { this.name = name; } - public GeoDistanceFilterBuilder point(double lat, double lon) { + public GeoDistanceQueryBuilder point(double lat, double lon) { this.lat = lat; this.lon = lon; return this; } - public GeoDistanceFilterBuilder lat(double lat) { + public GeoDistanceQueryBuilder lat(double lat) { this.lat = lat; return this; } - public GeoDistanceFilterBuilder lon(double lon) { + public GeoDistanceQueryBuilder lon(double lon) { this.lon = lon; return this; } - public GeoDistanceFilterBuilder distance(String distance) { + public GeoDistanceQueryBuilder distance(String distance) { this.distance = distance; return this; } - public GeoDistanceFilterBuilder distance(double distance, DistanceUnit unit) { + public GeoDistanceQueryBuilder distance(double distance, DistanceUnit unit) { this.distance = unit.toString(distance); return this; } - public GeoDistanceFilterBuilder geohash(String geohash) { + public GeoDistanceQueryBuilder geohash(String geohash) { this.geohash = geohash; return this; } - public GeoDistanceFilterBuilder geoDistance(GeoDistance geoDistance) { + public GeoDistanceQueryBuilder geoDistance(GeoDistance geoDistance) { this.geoDistance = geoDistance; return this; } - public GeoDistanceFilterBuilder optimizeBbox(String optimizeBbox) { + public GeoDistanceQueryBuilder optimizeBbox(String optimizeBbox) { this.optimizeBbox = optimizeBbox; return this; } @@ -95,14 +95,14 @@ public class GeoDistanceFilterBuilder extends BaseFilterBuilder { /** * Sets the filter name for the filter that can be used when searching for matched_filters per hit. */ - public GeoDistanceFilterBuilder filterName(String filterName) { - this.filterName = filterName; + public GeoDistanceQueryBuilder queryName(String queryName) { + this.queryName = queryName; return this; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(GeoDistanceFilterParser.NAME); + builder.startObject(GeoDistanceQueryParser.NAME); if (geohash != null) { builder.field(name, geohash); } else { @@ -115,8 +115,8 @@ public class GeoDistanceFilterBuilder extends BaseFilterBuilder { if (optimizeBbox != null) { builder.field("optimize_bbox", optimizeBbox); } - if (filterName != null) { - builder.field("_name", filterName); + if (queryName != null) { + builder.field("_name", queryName); } builder.endObject(); } diff --git a/src/main/java/org/elasticsearch/index/query/GeoDistanceFilterParser.java b/src/main/java/org/elasticsearch/index/query/GeoDistanceQueryParser.java similarity index 91% rename from src/main/java/org/elasticsearch/index/query/GeoDistanceFilterParser.java rename to src/main/java/org/elasticsearch/index/query/GeoDistanceQueryParser.java index ff46d591f3c..cae1d075a78 100644 --- a/src/main/java/org/elasticsearch/index/query/GeoDistanceFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/GeoDistanceQueryParser.java @@ -19,7 +19,7 @@ package org.elasticsearch.index.query; -import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.elasticsearch.common.geo.GeoDistance; import org.elasticsearch.common.geo.GeoHashUtils; import org.elasticsearch.common.geo.GeoPoint; @@ -43,12 +43,12 @@ import java.io.IOException; * } * */ -public class GeoDistanceFilterParser implements FilterParser { +public class GeoDistanceQueryParser implements QueryParser { public static final String NAME = "geo_distance"; @Inject - public GeoDistanceFilterParser() { + public GeoDistanceQueryParser() { } @Override @@ -57,12 +57,12 @@ public class GeoDistanceFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); XContentParser.Token token; - String filterName = null; + String queryName = null; String currentFieldName = null; GeoPoint point = new GeoPoint(); String fieldName = null; @@ -96,7 +96,7 @@ public class GeoDistanceFilterParser implements FilterParser { } else if (currentName.equals(GeoPointFieldMapper.Names.GEOHASH)) { GeoHashUtils.decode(parser.text(), point); } else { - throw new QueryParsingException(parseContext, "[geo_distance] filter does not support [" + currentFieldName + throw new QueryParsingException(parseContext, "[geo_distance] query does not support [" + currentFieldName + "]"); } } @@ -122,7 +122,7 @@ public class GeoDistanceFilterParser implements FilterParser { GeoHashUtils.decode(parser.text(), point); fieldName = currentFieldName.substring(0, currentFieldName.length() - GeoPointFieldMapper.Names.GEOHASH_SUFFIX.length()); } else if ("_name".equals(currentFieldName)) { - filterName = parser.text(); + queryName = parser.text(); } else if ("optimize_bbox".equals(currentFieldName) || "optimizeBbox".equals(currentFieldName)) { optimizeBbox = parser.textOrNull(); } else if ("normalize".equals(currentFieldName)) { @@ -160,10 +160,10 @@ public class GeoDistanceFilterParser implements FilterParser { IndexGeoPointFieldData indexFieldData = parseContext.getForField(mapper); - Filter filter = new GeoDistanceFilter(point.lat(), point.lon(), distance, geoDistance, indexFieldData, geoMapper, optimizeBbox); - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); + Query query = new GeoDistanceFilter(point.lat(), point.lon(), distance, geoDistance, indexFieldData, geoMapper, optimizeBbox); + if (queryName != null) { + parseContext.addNamedQuery(queryName, query); } - return filter; + return query; } } diff --git a/src/main/java/org/elasticsearch/index/query/GeoDistanceRangeFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/GeoDistanceRangeQueryBuilder.java similarity index 70% rename from src/main/java/org/elasticsearch/index/query/GeoDistanceRangeFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/GeoDistanceRangeQueryBuilder.java index c21cd3d62d7..e16680de1b6 100644 --- a/src/main/java/org/elasticsearch/index/query/GeoDistanceRangeFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/GeoDistanceRangeQueryBuilder.java @@ -28,7 +28,7 @@ import java.util.Locale; /** * */ -public class GeoDistanceRangeFilterBuilder extends BaseFilterBuilder { +public class GeoDistanceRangeQueryBuilder extends BaseQueryBuilder { private final String name; @@ -45,85 +45,85 @@ public class GeoDistanceRangeFilterBuilder extends BaseFilterBuilder { private GeoDistance geoDistance; - private String filterName; + private String queryName; private String optimizeBbox; - public GeoDistanceRangeFilterBuilder(String name) { + public GeoDistanceRangeQueryBuilder(String name) { this.name = name; } - public GeoDistanceRangeFilterBuilder point(double lat, double lon) { + public GeoDistanceRangeQueryBuilder point(double lat, double lon) { this.lat = lat; this.lon = lon; return this; } - public GeoDistanceRangeFilterBuilder lat(double lat) { + public GeoDistanceRangeQueryBuilder lat(double lat) { this.lat = lat; return this; } - public GeoDistanceRangeFilterBuilder lon(double lon) { + public GeoDistanceRangeQueryBuilder lon(double lon) { this.lon = lon; return this; } - public GeoDistanceRangeFilterBuilder from(Object from) { + public GeoDistanceRangeQueryBuilder from(Object from) { this.from = from; return this; } - public GeoDistanceRangeFilterBuilder to(Object to) { + public GeoDistanceRangeQueryBuilder to(Object to) { this.to = to; return this; } - public GeoDistanceRangeFilterBuilder gt(Object from) { + public GeoDistanceRangeQueryBuilder gt(Object from) { this.from = from; this.includeLower = false; return this; } - public GeoDistanceRangeFilterBuilder gte(Object from) { + public GeoDistanceRangeQueryBuilder gte(Object from) { this.from = from; this.includeLower = true; return this; } - public GeoDistanceRangeFilterBuilder lt(Object to) { + public GeoDistanceRangeQueryBuilder lt(Object to) { this.to = to; this.includeUpper = false; return this; } - public GeoDistanceRangeFilterBuilder lte(Object to) { + public GeoDistanceRangeQueryBuilder lte(Object to) { this.to = to; this.includeUpper = true; return this; } - public GeoDistanceRangeFilterBuilder includeLower(boolean includeLower) { + public GeoDistanceRangeQueryBuilder includeLower(boolean includeLower) { this.includeLower = includeLower; return this; } - public GeoDistanceRangeFilterBuilder includeUpper(boolean includeUpper) { + public GeoDistanceRangeQueryBuilder includeUpper(boolean includeUpper) { this.includeUpper = includeUpper; return this; } - public GeoDistanceRangeFilterBuilder geohash(String geohash) { + public GeoDistanceRangeQueryBuilder geohash(String geohash) { this.geohash = geohash; return this; } - public GeoDistanceRangeFilterBuilder geoDistance(GeoDistance geoDistance) { + public GeoDistanceRangeQueryBuilder geoDistance(GeoDistance geoDistance) { this.geoDistance = geoDistance; return this; } - public GeoDistanceRangeFilterBuilder optimizeBbox(String optimizeBbox) { + public GeoDistanceRangeQueryBuilder optimizeBbox(String optimizeBbox) { this.optimizeBbox = optimizeBbox; return this; } @@ -131,14 +131,14 @@ public class GeoDistanceRangeFilterBuilder extends BaseFilterBuilder { /** * Sets the filter name for the filter that can be used when searching for matched_filters per hit. */ - public GeoDistanceRangeFilterBuilder filterName(String filterName) { - this.filterName = filterName; + public GeoDistanceRangeQueryBuilder queryName(String queryName) { + this.queryName = queryName; return this; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(GeoDistanceRangeFilterParser.NAME); + builder.startObject(GeoDistanceRangeQueryParser.NAME); if (geohash != null) { builder.field(name, geohash); } else { @@ -154,8 +154,8 @@ public class GeoDistanceRangeFilterBuilder extends BaseFilterBuilder { if (optimizeBbox != null) { builder.field("optimize_bbox", optimizeBbox); } - if (filterName != null) { - builder.field("_name", filterName); + if (queryName != null) { + builder.field("_name", queryName); } builder.endObject(); } diff --git a/src/main/java/org/elasticsearch/index/query/GeoDistanceRangeFilterParser.java b/src/main/java/org/elasticsearch/index/query/GeoDistanceRangeQueryParser.java similarity index 93% rename from src/main/java/org/elasticsearch/index/query/GeoDistanceRangeFilterParser.java rename to src/main/java/org/elasticsearch/index/query/GeoDistanceRangeQueryParser.java index 9322a230c01..9425f3a8913 100644 --- a/src/main/java/org/elasticsearch/index/query/GeoDistanceRangeFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/GeoDistanceRangeQueryParser.java @@ -19,7 +19,7 @@ package org.elasticsearch.index.query; -import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.elasticsearch.common.geo.GeoDistance; import org.elasticsearch.common.geo.GeoHashUtils; import org.elasticsearch.common.geo.GeoPoint; @@ -43,12 +43,12 @@ import java.io.IOException; * } * */ -public class GeoDistanceRangeFilterParser implements FilterParser { +public class GeoDistanceRangeQueryParser implements QueryParser { public static final String NAME = "geo_distance_range"; @Inject - public GeoDistanceRangeFilterParser() { + public GeoDistanceRangeQueryParser() { } @Override @@ -57,12 +57,12 @@ public class GeoDistanceRangeFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); XContentParser.Token token; - String filterName = null; + String queryName = null; String currentFieldName = null; GeoPoint point = new GeoPoint(); String fieldName = null; @@ -152,7 +152,7 @@ public class GeoDistanceRangeFilterParser implements FilterParser { GeoHashUtils.decode(parser.text(), point); fieldName = currentFieldName.substring(0, currentFieldName.length() - GeoPointFieldMapper.Names.GEOHASH_SUFFIX.length()); } else if ("_name".equals(currentFieldName)) { - filterName = parser.text(); + queryName = parser.text(); } else if ("optimize_bbox".equals(currentFieldName) || "optimizeBbox".equals(currentFieldName)) { optimizeBbox = parser.textOrNull(); } else if ("normalize".equals(currentFieldName)) { @@ -199,10 +199,10 @@ public class GeoDistanceRangeFilterParser implements FilterParser { GeoPointFieldMapper geoMapper = ((GeoPointFieldMapper) mapper); IndexGeoPointFieldData indexFieldData = parseContext.getForField(mapper); - Filter filter = new GeoDistanceRangeFilter(point, from, to, includeLower, includeUpper, geoDistance, geoMapper, indexFieldData, optimizeBbox); - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); + Query query = new GeoDistanceRangeFilter(point, from, to, includeLower, includeUpper, geoDistance, geoMapper, indexFieldData, optimizeBbox); + if (queryName != null) { + parseContext.addNamedQuery(queryName, query); } - return filter; + return query; } } diff --git a/src/main/java/org/elasticsearch/index/query/GeoPolygonFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/GeoPolygonQueryBuilder.java similarity index 76% rename from src/main/java/org/elasticsearch/index/query/GeoPolygonFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/GeoPolygonQueryBuilder.java index fd0a2f569c4..609eb55d656 100644 --- a/src/main/java/org/elasticsearch/index/query/GeoPolygonFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/GeoPolygonQueryBuilder.java @@ -31,17 +31,17 @@ import java.util.List; /** * */ -public class GeoPolygonFilterBuilder extends BaseFilterBuilder { +public class GeoPolygonQueryBuilder extends BaseQueryBuilder { - public static final String POINTS = GeoPolygonFilterParser.POINTS; + public static final String POINTS = GeoPolygonQueryParser.POINTS; private final String name; private final List shell = Lists.newArrayList(); - private String filterName; + private String queryName; - public GeoPolygonFilterBuilder(String name) { + public GeoPolygonQueryBuilder(String name) { this.name = name; } @@ -52,15 +52,15 @@ public class GeoPolygonFilterBuilder extends BaseFilterBuilder { * @param lon The longitude * @return */ - public GeoPolygonFilterBuilder addPoint(double lat, double lon) { + public GeoPolygonQueryBuilder addPoint(double lat, double lon) { return addPoint(new GeoPoint(lat, lon)); } - public GeoPolygonFilterBuilder addPoint(String geohash) { + public GeoPolygonQueryBuilder addPoint(String geohash) { return addPoint(GeoHashUtils.decode(geohash)); } - public GeoPolygonFilterBuilder addPoint(GeoPoint point) { + public GeoPolygonQueryBuilder addPoint(GeoPoint point) { shell.add(point); return this; } @@ -68,14 +68,14 @@ public class GeoPolygonFilterBuilder extends BaseFilterBuilder { /** * Sets the filter name for the filter that can be used when searching for matched_filters per hit. */ - public GeoPolygonFilterBuilder filterName(String filterName) { - this.filterName = filterName; + public GeoPolygonQueryBuilder queryName(String queryName) { + this.queryName = queryName; return this; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(GeoPolygonFilterParser.NAME); + builder.startObject(GeoPolygonQueryParser.NAME); builder.startObject(name); builder.startArray(POINTS); @@ -85,8 +85,8 @@ public class GeoPolygonFilterBuilder extends BaseFilterBuilder { builder.endArray(); builder.endObject(); - if (filterName != null) { - builder.field("_name", filterName); + if (queryName != null) { + builder.field("_name", queryName); } builder.endObject(); diff --git a/src/main/java/org/elasticsearch/index/query/GeoPolygonFilterParser.java b/src/main/java/org/elasticsearch/index/query/GeoPolygonQueryParser.java similarity index 85% rename from src/main/java/org/elasticsearch/index/query/GeoPolygonFilterParser.java rename to src/main/java/org/elasticsearch/index/query/GeoPolygonQueryParser.java index f3f41ac7126..61853a34394 100644 --- a/src/main/java/org/elasticsearch/index/query/GeoPolygonFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/GeoPolygonQueryParser.java @@ -21,7 +21,7 @@ package org.elasticsearch.index.query; import com.google.common.collect.Lists; -import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.geo.GeoUtils; import org.elasticsearch.common.inject.Inject; @@ -48,13 +48,13 @@ import java.util.List; * } * */ -public class GeoPolygonFilterParser implements FilterParser { +public class GeoPolygonQueryParser implements QueryParser { public static final String NAME = "geo_polygon"; public static final String POINTS = "points"; @Inject - public GeoPolygonFilterParser() { + public GeoPolygonQueryParser() { } @Override @@ -63,7 +63,7 @@ public class GeoPolygonFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); String fieldName = null; @@ -73,7 +73,7 @@ public class GeoPolygonFilterParser implements FilterParser { boolean normalizeLon = true; boolean normalizeLat = true; - String filterName = null; + String queryName = null; String currentFieldName = null; XContentParser.Token token; @@ -94,22 +94,22 @@ public class GeoPolygonFilterParser implements FilterParser { shell.add(GeoUtils.parseGeoPoint(parser)); } } else { - throw new QueryParsingException(parseContext, "[geo_polygon] filter does not support [" + currentFieldName + throw new QueryParsingException(parseContext, "[geo_polygon] query does not support [" + currentFieldName + "]"); } } else { - throw new QueryParsingException(parseContext, "[geo_polygon] filter does not support token type [" + token.name() + throw new QueryParsingException(parseContext, "[geo_polygon] query does not support token type [" + token.name() + "] under [" + currentFieldName + "]"); } } } else if (token.isValue()) { if ("_name".equals(currentFieldName)) { - filterName = parser.text(); + queryName = parser.text(); } else if ("normalize".equals(currentFieldName)) { normalizeLat = parser.booleanValue(); normalizeLon = parser.booleanValue(); } else { - throw new QueryParsingException(parseContext, "[geo_polygon] filter does not support [" + currentFieldName + "]"); + throw new QueryParsingException(parseContext, "[geo_polygon] query does not support [" + currentFieldName + "]"); } } else { throw new QueryParsingException(parseContext, "[geo_polygon] unexpected token type [" + token.name() + "]"); @@ -117,17 +117,17 @@ public class GeoPolygonFilterParser implements FilterParser { } if (shell.isEmpty()) { - throw new QueryParsingException(parseContext, "no points defined for geo_polygon filter"); + throw new QueryParsingException(parseContext, "no points defined for geo_polygon query"); } else { if (shell.size() < 3) { - throw new QueryParsingException(parseContext, "too few points defined for geo_polygon filter"); + throw new QueryParsingException(parseContext, "too few points defined for geo_polygon query"); } GeoPoint start = shell.get(0); if (!start.equals(shell.get(shell.size() - 1))) { shell.add(start); } if (shell.size() < 4) { - throw new QueryParsingException(parseContext, "too few points defined for geo_polygon filter"); + throw new QueryParsingException(parseContext, "too few points defined for geo_polygon query"); } } @@ -147,10 +147,10 @@ public class GeoPolygonFilterParser implements FilterParser { } IndexGeoPointFieldData indexFieldData = parseContext.getForField(mapper); - Filter filter = new GeoPolygonFilter(indexFieldData, shell.toArray(new GeoPoint[shell.size()])); - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); + Query query = new GeoPolygonFilter(indexFieldData, shell.toArray(new GeoPoint[shell.size()])); + if (queryName != null) { + parseContext.addNamedQuery(queryName, query); } - return filter; + return query; } } diff --git a/src/main/java/org/elasticsearch/index/query/GeoShapeFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/GeoShapeFilterBuilder.java deleted file mode 100644 index 1ac7b14481c..00000000000 --- a/src/main/java/org/elasticsearch/index/query/GeoShapeFilterBuilder.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.common.geo.ShapeRelation; -import org.elasticsearch.common.geo.SpatialStrategy; -import org.elasticsearch.common.geo.builders.ShapeBuilder; -import org.elasticsearch.common.xcontent.XContentBuilder; - -import java.io.IOException; - -/** - * {@link FilterBuilder} that builds a GeoShape Filter - */ -public class GeoShapeFilterBuilder extends BaseFilterBuilder { - - private final String name; - - private final ShapeBuilder shape; - - private SpatialStrategy strategy = null; - - private String filterName; - - private final String indexedShapeId; - private final String indexedShapeType; - - private String indexedShapeIndex; - private String indexedShapePath; - - private ShapeRelation relation = null; - - /** - * Creates a new GeoShapeFilterBuilder whose Filter will be against the - * given field name using the given Shape - * - * @param name Name of the field that will be filtered - * @param shape Shape used in the filter - */ - public GeoShapeFilterBuilder(String name, ShapeBuilder shape) { - this(name, shape, null, null, null); - } - - /** - * Creates a new GeoShapeFilterBuilder whose Filter will be against the - * given field name using the given Shape - * - * @param name Name of the field that will be filtered - * @param relation {@link ShapeRelation} of query and indexed shape - * @param shape Shape used in the filter - */ - public GeoShapeFilterBuilder(String name, ShapeBuilder shape, ShapeRelation relation) { - this(name, shape, null, null, relation); - } - - /** - * Creates a new GeoShapeFilterBuilder whose Filter will be against the given field name - * and will use the Shape found with the given ID in the given type - * - * @param name Name of the field that will be filtered - * @param indexedShapeId ID of the indexed Shape that will be used in the Filter - * @param indexedShapeType Index type of the indexed Shapes - */ - public GeoShapeFilterBuilder(String name, String indexedShapeId, String indexedShapeType, ShapeRelation relation) { - this(name, null, indexedShapeId, indexedShapeType, relation); - } - - private GeoShapeFilterBuilder(String name, ShapeBuilder shape, String indexedShapeId, String indexedShapeType, ShapeRelation relation) { - this.name = name; - this.shape = shape; - this.indexedShapeId = indexedShapeId; - this.relation = relation; - this.indexedShapeType = indexedShapeType; - } - - /** - * Sets the name of the filter - * - * @param filterName Name of the filter - * @return this - */ - public GeoShapeFilterBuilder filterName(String filterName) { - this.filterName = filterName; - return this; - } - - /** - * Defines which spatial strategy will be used for building the geo shape filter. When not set, the strategy that - * will be used will be the one that is associated with the geo shape field in the mappings. - * - * @param strategy The spatial strategy to use for building the geo shape filter - * @return this - */ - public GeoShapeFilterBuilder strategy(SpatialStrategy strategy) { - this.strategy = strategy; - return this; - } - - /** - * Sets the name of the index where the indexed Shape can be found - * - * @param indexedShapeIndex Name of the index where the indexed Shape is - * @return this - */ - public GeoShapeFilterBuilder indexedShapeIndex(String indexedShapeIndex) { - this.indexedShapeIndex = indexedShapeIndex; - return this; - } - - /** - * Sets the path of the field in the indexed Shape document that has the Shape itself - * - * @param indexedShapePath Path of the field where the Shape itself is defined - * @return this - */ - public GeoShapeFilterBuilder indexedShapePath(String indexedShapePath) { - this.indexedShapePath = indexedShapePath; - return this; - } - - /** - * Sets the relation of query shape and indexed shape. - * - * @param relation relation of the shapes - * @return this - */ - public GeoShapeFilterBuilder relation(ShapeRelation relation) { - this.relation = relation; - return this; - } - - @Override - protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(GeoShapeFilterParser.NAME); - - builder.startObject(name); - - if (strategy != null) { - builder.field("strategy", strategy.getStrategyName()); - } - - if (shape != null) { - builder.field("shape", shape); - } else { - builder.startObject("indexed_shape") - .field("id", indexedShapeId) - .field("type", indexedShapeType); - if (indexedShapeIndex != null) { - builder.field("index", indexedShapeIndex); - } - if (indexedShapePath != null) { - builder.field("path", indexedShapePath); - } - builder.endObject(); - } - - if(relation != null) { - builder.field("relation", relation.getRelationName()); - } - - builder.endObject(); - - if (name != null) { - builder.field("_name", filterName); - } - - builder.endObject(); - } -} diff --git a/src/main/java/org/elasticsearch/index/query/GeoShapeFilterParser.java b/src/main/java/org/elasticsearch/index/query/GeoShapeFilterParser.java deleted file mode 100644 index bba22882d27..00000000000 --- a/src/main/java/org/elasticsearch/index/query/GeoShapeFilterParser.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import com.spatial4j.core.shape.Shape; - -import org.apache.lucene.search.BooleanClause; -import org.apache.lucene.search.BooleanQuery; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.QueryWrapperFilter; -import org.apache.lucene.spatial.prefix.PrefixTreeStrategy; -import org.apache.lucene.spatial.prefix.RecursivePrefixTreeStrategy; -import org.elasticsearch.common.geo.ShapeRelation; -import org.elasticsearch.common.geo.builders.ShapeBuilder; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.inject.internal.Nullable; -import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.mapper.FieldMapper; -import org.elasticsearch.index.mapper.MapperService; -import org.elasticsearch.index.mapper.geo.GeoShapeFieldMapper; -import org.elasticsearch.index.search.shape.ShapeFetchService; - -import java.io.IOException; - -/** - * {@link FilterParser} for filtering Documents based on {@link Shape}s. - *

- * Only those fields mapped using {@link GeoShapeFieldMapper} can be filtered - * using this parser. - *

- * Format supported: - *

- *

- * "field" : {
- *     "relation" : "intersects",
- *     "shape" : {
- *         "type" : "polygon",
- *         "coordinates" : [
- *              [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]
- *         ]
- *     }
- * }
- * 
- */ -public class GeoShapeFilterParser implements FilterParser { - - public static final String NAME = "geo_shape"; - - private ShapeFetchService fetchService; - - public static class DEFAULTS { - public static final String INDEX_NAME = "shapes"; - public static final String SHAPE_FIELD_NAME = "shape"; - } - - @Override - public String[] names() { - return new String[]{NAME, "geoShape"}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - String fieldName = null; - ShapeRelation shapeRelation = ShapeRelation.INTERSECTS; - String strategyName = null; - ShapeBuilder shape = null; - String filterName = null; - - String id = null; - String type = null; - String index = DEFAULTS.INDEX_NAME; - String shapePath = DEFAULTS.SHAPE_FIELD_NAME; - - XContentParser.Token token; - String currentFieldName = null; - - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (parseContext.isDeprecatedSetting(currentFieldName)) { - // skip - } else if (token == XContentParser.Token.START_OBJECT) { - fieldName = currentFieldName; - - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - - token = parser.nextToken(); - if ("shape".equals(currentFieldName)) { - shape = ShapeBuilder.parse(parser); - } else if ("relation".equals(currentFieldName)) { - shapeRelation = ShapeRelation.getRelationByName(parser.text()); - if (shapeRelation == null) { - throw new QueryParsingException(parseContext, "Unknown shape operation [" + parser.text() + "]"); - } - } else if ("strategy".equals(currentFieldName)) { - strategyName = parser.text(); - } else if ("indexed_shape".equals(currentFieldName) || "indexedShape".equals(currentFieldName)) { - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (token.isValue()) { - if ("id".equals(currentFieldName)) { - id = parser.text(); - } else if ("type".equals(currentFieldName)) { - type = parser.text(); - } else if ("index".equals(currentFieldName)) { - index = parser.text(); - } else if ("path".equals(currentFieldName)) { - shapePath = parser.text(); - } - } - } - if (id == null) { - throw new QueryParsingException(parseContext, "ID for indexed shape not provided"); - } else if (type == null) { - throw new QueryParsingException(parseContext, "Type for indexed shape not provided"); - } - shape = fetchService.fetch(id, type, index, shapePath); - } else { - throw new QueryParsingException(parseContext, "[geo_shape] filter does not support [" + currentFieldName + "]"); - } - } - } - } else if (token.isValue()) { - if ("_name".equals(currentFieldName)) { - filterName = parser.text(); - } else { - throw new QueryParsingException(parseContext, "[geo_shape] filter does not support [" + currentFieldName + "]"); - } - } - } - - if (shape == null) { - throw new QueryParsingException(parseContext, "No Shape defined"); - } else if (shapeRelation == null) { - throw new QueryParsingException(parseContext, "No Shape Relation defined"); - } - - MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); - if (smartNameFieldMappers == null || !smartNameFieldMappers.hasMapper()) { - throw new QueryParsingException(parseContext, "Failed to find geo_shape field [" + fieldName + "]"); - } - - FieldMapper fieldMapper = smartNameFieldMappers.mapper(); - // TODO: This isn't the nicest way to check this - if (!(fieldMapper instanceof GeoShapeFieldMapper)) { - throw new QueryParsingException(parseContext, "Field [" + fieldName + "] is not a geo_shape"); - } - - GeoShapeFieldMapper shapeFieldMapper = (GeoShapeFieldMapper) fieldMapper; - PrefixTreeStrategy strategy = shapeFieldMapper.defaultStrategy(); - if (strategyName != null) { - strategy = shapeFieldMapper.resolveStrategy(strategyName); - } - - Filter filter; - if (strategy instanceof RecursivePrefixTreeStrategy && shapeRelation == ShapeRelation.DISJOINT) { - // this strategy doesn't support disjoint anymore: but it did before, including creating lucene fieldcache (!) - // in this case, execute disjoint as exists && !intersects - BooleanQuery bool = new BooleanQuery(); - Filter exists = ExistsFilterParser.newFilter(parseContext, fieldName, null); - Filter intersects = strategy.makeFilter(GeoShapeQueryParser.getArgs(shape, ShapeRelation.INTERSECTS)); - bool.add(exists, BooleanClause.Occur.MUST); - bool.add(intersects, BooleanClause.Occur.MUST_NOT); - filter = new QueryWrapperFilter(bool); - } else { - filter = strategy.makeFilter(GeoShapeQueryParser.getArgs(shape, shapeRelation)); - } - - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); - } - - return filter; - } - - @Inject(optional = true) - public void setFetchService(@Nullable ShapeFetchService fetchService) { - this.fetchService = fetchService; - } -} diff --git a/src/main/java/org/elasticsearch/index/query/GeoShapeQueryBuilder.java b/src/main/java/org/elasticsearch/index/query/GeoShapeQueryBuilder.java index efda63bd355..7e1beb19180 100644 --- a/src/main/java/org/elasticsearch/index/query/GeoShapeQueryBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/GeoShapeQueryBuilder.java @@ -19,6 +19,7 @@ package org.elasticsearch.index.query; +import org.elasticsearch.common.geo.ShapeRelation; import org.elasticsearch.common.geo.SpatialStrategy; import org.elasticsearch.common.geo.builders.ShapeBuilder; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -26,17 +27,17 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; /** - * {@link QueryBuilder} that builds a GeoShape Query + * {@link QueryBuilder} that builds a GeoShape Filter */ -public class GeoShapeQueryBuilder extends BaseQueryBuilder implements BoostableQueryBuilder { +public class GeoShapeQueryBuilder extends BaseQueryBuilder { private final String name; - private SpatialStrategy strategy = null; - private final ShapeBuilder shape; - private float boost = -1; + private SpatialStrategy strategy = null; + + private String queryName; private final String indexedShapeId; private final String indexedShapeType; @@ -44,52 +45,67 @@ public class GeoShapeQueryBuilder extends BaseQueryBuilder implements BoostableQ private String indexedShapeIndex; private String indexedShapePath; - private String queryName; - + private ShapeRelation relation = null; + /** - * Creates a new GeoShapeQueryBuilder whose Query will be against the + * Creates a new GeoShapeQueryBuilder whose Filter will be against the * given field name using the given Shape * - * @param name Name of the field that will be queried - * @param shape Shape used in the query + * @param name Name of the field that will be filtered + * @param shape Shape used in the filter */ public GeoShapeQueryBuilder(String name, ShapeBuilder shape) { - this(name, shape, null, null); + this(name, shape, null, null, null); } /** - * Creates a new GeoShapeQueryBuilder whose Query will be against the given field name - * and will use the Shape found with the given ID in the given type + * Creates a new GeoShapeQueryBuilder whose Filter will be against the + * given field name using the given Shape * - * @param name Name of the field that will be queried - * @param indexedShapeId ID of the indexed Shape that will be used in the Query - * @param indexedShapeType Index type of the indexed Shapes + * @param name Name of the field that will be filtered + * @param relation {@link ShapeRelation} of query and indexed shape + * @param shape Shape used in the filter */ - public GeoShapeQueryBuilder(String name, String indexedShapeId, String indexedShapeType) { - this(name, null, indexedShapeId, indexedShapeType); + public GeoShapeQueryBuilder(String name, ShapeBuilder shape, ShapeRelation relation) { + this(name, shape, null, null, relation); } - private GeoShapeQueryBuilder(String name, ShapeBuilder shape, String indexedShapeId, String indexedShapeType) { + /** + * Creates a new GeoShapeQueryBuilder whose Filter will be against the given field name + * and will use the Shape found with the given ID in the given type + * + * @param name Name of the field that will be filtered + * @param indexedShapeId ID of the indexed Shape that will be used in the Filter + * @param indexedShapeType Index type of the indexed Shapes + */ + public GeoShapeQueryBuilder(String name, String indexedShapeId, String indexedShapeType, ShapeRelation relation) { + this(name, null, indexedShapeId, indexedShapeType, relation); + } + + private GeoShapeQueryBuilder(String name, ShapeBuilder shape, String indexedShapeId, String indexedShapeType, ShapeRelation relation) { this.name = name; this.shape = shape; this.indexedShapeId = indexedShapeId; + this.relation = relation; this.indexedShapeType = indexedShapeType; } /** - * {@inheritDoc} + * Sets the name of the filter + * + * @param queryName Name of the filter + * @return this */ - @Override - public GeoShapeQueryBuilder boost(float boost) { - this.boost = boost; + public GeoShapeQueryBuilder queryName(String queryName) { + this.queryName = queryName; return this; } /** - * Defines which spatial strategy will be used for building the geo shape query. When not set, the strategy that + * Defines which spatial strategy will be used for building the geo shape filter. When not set, the strategy that * will be used will be the one that is associated with the geo shape field in the mappings. * - * @param strategy The spatial strategy to use for building the geo shape query + * @param strategy The spatial strategy to use for building the geo shape filter * @return this */ public GeoShapeQueryBuilder strategy(SpatialStrategy strategy) { @@ -111,7 +127,7 @@ public class GeoShapeQueryBuilder extends BaseQueryBuilder implements BoostableQ /** * Sets the path of the field in the indexed Shape document that has the Shape itself * - * @param indexedShapePath path of the field where the Shape itself is defined + * @param indexedShapePath Path of the field where the Shape itself is defined * @return this */ public GeoShapeQueryBuilder indexedShapePath(String indexedShapePath) { @@ -120,10 +136,13 @@ public class GeoShapeQueryBuilder extends BaseQueryBuilder implements BoostableQ } /** - * Sets the query name for the filter that can be used when searching for matched_filters per hit. + * Sets the relation of query shape and indexed shape. + * + * @param relation relation of the shapes + * @return this */ - public GeoShapeQueryBuilder queryName(String queryName) { - this.queryName = queryName; + public GeoShapeQueryBuilder relation(ShapeRelation relation) { + this.relation = relation; return this; } @@ -152,16 +171,16 @@ public class GeoShapeQueryBuilder extends BaseQueryBuilder implements BoostableQ builder.endObject(); } - if (boost != -1) { - builder.field("boost", boost); + if(relation != null) { + builder.field("relation", relation.getRelationName()); } - if (queryName != null) { + + builder.endObject(); + + if (name != null) { builder.field("_name", queryName); } builder.endObject(); - - builder.endObject(); } - } diff --git a/src/main/java/org/elasticsearch/index/query/GeoShapeQueryParser.java b/src/main/java/org/elasticsearch/index/query/GeoShapeQueryParser.java index ac3d4f59f92..ffe72547fb5 100644 --- a/src/main/java/org/elasticsearch/index/query/GeoShapeQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/GeoShapeQueryParser.java @@ -161,7 +161,7 @@ public class GeoShapeQueryParser implements QueryParser { // this strategy doesn't support disjoint anymore: but it did before, including creating lucene fieldcache (!) // in this case, execute disjoint as exists && !intersects BooleanQuery bool = new BooleanQuery(); - Filter exists = ExistsFilterParser.newFilter(parseContext, fieldName, null); + Query exists = ExistsQueryParser.newFilter(parseContext, fieldName, null); Filter intersects = strategy.makeFilter(getArgs(shape, ShapeRelation.INTERSECTS)); bool.add(exists, BooleanClause.Occur.MUST); bool.add(intersects, BooleanClause.Occur.MUST_NOT); diff --git a/src/main/java/org/elasticsearch/index/query/GeohashCellFilter.java b/src/main/java/org/elasticsearch/index/query/GeohashCellQuery.java similarity index 93% rename from src/main/java/org/elasticsearch/index/query/GeohashCellFilter.java rename to src/main/java/org/elasticsearch/index/query/GeohashCellQuery.java index e390bf53ea7..c2ec86d182a 100644 --- a/src/main/java/org/elasticsearch/index/query/GeohashCellFilter.java +++ b/src/main/java/org/elasticsearch/index/query/GeohashCellQuery.java @@ -19,7 +19,7 @@ package org.elasticsearch.index.query; -import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; @@ -46,7 +46,7 @@ import java.util.List; * prefix will be returned. The neighbors flag allows to filter * geohashes that surround the given geohash. In general the neighborhood of a * geohash is defined by its eight adjacent cells.
- * The structure of the {@link GeohashCellFilter} is defined as: + * The structure of the {@link GeohashCellQuery} is defined as: *
  * "geohash_bbox" {
  *     "field":"location",
@@ -55,7 +55,7 @@ import java.util.List;
  * }
  * 
*/ -public class GeohashCellFilter { +public class GeohashCellQuery { public static final String NAME = "geohash_cell"; public static final String NEIGHBORS = "neighbors"; @@ -71,17 +71,17 @@ public class GeohashCellFilter { * @param geohashes optional array of additional geohashes * @return a new GeoBoundinboxfilter */ - public static Filter create(QueryParseContext context, GeoPointFieldMapper fieldMapper, String geohash, @Nullable List geohashes) { + public static Query create(QueryParseContext context, GeoPointFieldMapper fieldMapper, String geohash, @Nullable List geohashes) { if (fieldMapper.geoHashStringMapper() == null) { throw new IllegalArgumentException("geohash filter needs geohash_prefix to be enabled"); } StringFieldMapper geoHashMapper = fieldMapper.geoHashStringMapper(); if (geohashes == null || geohashes.size() == 0) { - return geoHashMapper.termFilter(geohash, context); + return geoHashMapper.termQuery(geohash, context); } else { geohashes.add(geohash); - return geoHashMapper.termsFilter(geohashes, context); + return geoHashMapper.termsQuery(geohashes, context); } } @@ -90,7 +90,7 @@ public class GeohashCellFilter { * geohash to be set. the default for a neighbor filteing is * false. */ - public static class Builder extends BaseFilterBuilder { + public static class Builder extends BaseQueryBuilder { // we need to store the geohash rather than the corresponding point, // because a transformation from a geohash to a point an back to the // geohash will extend the accuracy of the hash to max precision @@ -170,7 +170,7 @@ public class GeohashCellFilter { } } - public static class Parser implements FilterParser { + public static class Parser implements QueryParser { @Inject public Parser() { @@ -182,7 +182,7 @@ public class GeohashCellFilter { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); String fieldName = null; @@ -258,7 +258,7 @@ public class GeohashCellFilter { geohash = geohash.substring(0, len); } - Filter filter; + Query filter; if (neighbors) { filter = create(parseContext, geoMapper, geohash, GeoHashUtils.addNeighbors(geohash, new ArrayList(8))); } else { diff --git a/src/main/java/org/elasticsearch/index/query/HasChildFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/HasChildFilterBuilder.java deleted file mode 100644 index 365d30b4e29..00000000000 --- a/src/main/java/org/elasticsearch/index/query/HasChildFilterBuilder.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.elasticsearch.index.query; - -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.support.QueryInnerHitBuilder; - -import java.io.IOException; - -/** - * - */ -public class HasChildFilterBuilder extends BaseFilterBuilder { - - private final FilterBuilder filterBuilder; - private final QueryBuilder queryBuilder; - private String childType; - private String filterName; - private Integer shortCircuitCutoff; - private Integer minChildren; - private Integer maxChildren; - private QueryInnerHitBuilder innerHit = null; - - public HasChildFilterBuilder(String type, QueryBuilder queryBuilder) { - this.childType = type; - this.queryBuilder = queryBuilder; - this.filterBuilder = null; - } - - public HasChildFilterBuilder(String type, FilterBuilder filterBuilder) { - this.childType = type; - this.queryBuilder = null; - this.filterBuilder = filterBuilder; - } - - /** - * Sets the filter name for the filter that can be used when searching for matched_filters per hit. - */ - public HasChildFilterBuilder filterName(String filterName) { - this.filterName = filterName; - return this; - } - - /** - * Defines the minimum number of children that are required to match for the parent to be considered a match. - */ - public HasChildFilterBuilder minChildren(int minChildren) { - this.minChildren = minChildren; - return this; - } - - /** - * Defines the maximum number of children that are required to match for the parent to be considered a match. - */ - public HasChildFilterBuilder maxChildren(int maxChildren) { - this.maxChildren = maxChildren; - return this; - } - - - /** - * This is a noop since has_child can't be cached. - */ - public HasChildFilterBuilder cache(boolean cache) { - return this; - } - - /** - * This is a noop since has_child can't be cached. - */ - public HasChildFilterBuilder cacheKey(String cacheKey) { - return this; - } - - /** - * Configures at what cut off point only to evaluate parent documents that contain the matching parent id terms - * instead of evaluating all parent docs. - */ - public HasChildFilterBuilder setShortCircuitCutoff(int shortCircuitCutoff) { - this.shortCircuitCutoff = shortCircuitCutoff; - return this; - } - - /** - * Sets inner hit definition in the scope of this filter and reusing the defined type and query. - */ - public HasChildFilterBuilder innerHit(QueryInnerHitBuilder innerHit) { - this.innerHit = innerHit; - return this; - } - - @Override - protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(HasChildFilterParser.NAME); - if (queryBuilder != null) { - builder.field("query"); - queryBuilder.toXContent(builder, params); - } else if (filterBuilder != null) { - builder.field("filter"); - filterBuilder.toXContent(builder, params); - } - builder.field("child_type", childType); - if (minChildren != null) { - builder.field("min_children", minChildren); - } - if (maxChildren != null) { - builder.field("max_children", maxChildren); - } - if (filterName != null) { - builder.field("_name", filterName); - } - if (shortCircuitCutoff != null) { - builder.field("short_circuit_cutoff", shortCircuitCutoff); - } - if (innerHit != null) { - builder.startObject("inner_hits"); - builder.value(innerHit); - builder.endObject(); - } - builder.endObject(); - } -} - diff --git a/src/main/java/org/elasticsearch/index/query/HasChildFilterParser.java b/src/main/java/org/elasticsearch/index/query/HasChildFilterParser.java deleted file mode 100644 index 8bf761b84a0..00000000000 --- a/src/main/java/org/elasticsearch/index/query/HasChildFilterParser.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.elasticsearch.index.query; - -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.FilteredQuery; -import org.apache.lucene.search.Query; -import org.apache.lucene.search.QueryWrapperFilter; -import org.apache.lucene.search.join.BitDocIdSetFilter; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.collect.Tuple; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.lucene.search.Queries; -import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.fielddata.plain.ParentChildIndexFieldData; -import org.elasticsearch.index.mapper.DocumentMapper; -import org.elasticsearch.index.mapper.internal.ParentFieldMapper; -import org.elasticsearch.index.query.support.InnerHitsQueryParserHelper; -import org.elasticsearch.index.query.support.XContentStructure; -import org.elasticsearch.index.search.child.ChildrenConstantScoreQuery; -import org.elasticsearch.index.search.child.ChildrenQuery; -import org.elasticsearch.index.search.child.ScoreType; -import org.elasticsearch.search.fetch.innerhits.InnerHitsContext; -import org.elasticsearch.search.internal.SubSearchContext; - -import java.io.IOException; - -/** - * - */ -public class HasChildFilterParser implements FilterParser { - - public static final String NAME = "has_child"; - - private final InnerHitsQueryParserHelper innerHitsQueryParserHelper; - - @Inject - public HasChildFilterParser(InnerHitsQueryParserHelper innerHitsQueryParserHelper) { - this.innerHitsQueryParserHelper = innerHitsQueryParserHelper; - } - - @Override - public String[] names() { - return new String[]{NAME, Strings.toCamelCase(NAME)}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - boolean queryFound = false; - boolean filterFound = false; - String childType = null; - int shortCircuitParentDocSet = 8192; // Tests show a cut of point between 8192 and 16384. - int minChildren = 0; - int maxChildren = 0; - Tuple innerHits = null; - - String filterName = null; - String currentFieldName = null; - XContentParser.Token token; - XContentStructure.InnerQuery innerQuery = null; - XContentStructure.InnerFilter innerFilter = null; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (parseContext.isDeprecatedSetting(currentFieldName)) { - // skip - } else if (token == XContentParser.Token.START_OBJECT) { - // Usually, the query would be parsed here, but the child - // type may not have been extracted yet, so use the - // XContentStructure. facade to parse if available, - // or delay parsing if not. - if ("query".equals(currentFieldName)) { - innerQuery = new XContentStructure.InnerQuery(parseContext, childType == null ? null : new String[] {childType}); - queryFound = true; - } else if ("filter".equals(currentFieldName)) { - innerFilter = new XContentStructure.InnerFilter(parseContext, childType == null ? null : new String[] {childType}); - filterFound = true; - } else if ("inner_hits".equals(currentFieldName)) { - innerHits = innerHitsQueryParserHelper.parse(parseContext); - } else { - throw new QueryParsingException(parseContext, "[has_child] filter does not support [" + currentFieldName + "]"); - } - } else if (token.isValue()) { - if ("type".equals(currentFieldName) || "child_type".equals(currentFieldName) || "childType".equals(currentFieldName)) { - childType = parser.text(); - } else if ("_name".equals(currentFieldName)) { - filterName = parser.text(); - } else if ("short_circuit_cutoff".equals(currentFieldName)) { - shortCircuitParentDocSet = parser.intValue(); - } else if ("min_children".equals(currentFieldName) || "minChildren".equals(currentFieldName)) { - minChildren = parser.intValue(true); - } else if ("max_children".equals(currentFieldName) || "maxChildren".equals(currentFieldName)) { - maxChildren = parser.intValue(true); - } else { - throw new QueryParsingException(parseContext, "[has_child] filter does not support [" + currentFieldName + "]"); - } - } - } - if (!queryFound && !filterFound) { - throw new QueryParsingException(parseContext, "[has_child] filter requires 'query' or 'filter' field"); - } - if (childType == null) { - throw new QueryParsingException(parseContext, "[has_child] filter requires 'type' field"); - } - - Query query; - if (queryFound) { - query = innerQuery.asQuery(childType); - } else { - query = innerFilter.asFilter(childType); - } - - if (query == null) { - return null; - } - - DocumentMapper childDocMapper = parseContext.mapperService().documentMapper(childType); - if (childDocMapper == null) { - throw new QueryParsingException(parseContext, "No mapping for for type [" + childType + "]"); - } - if (innerHits != null) { - InnerHitsContext.ParentChildInnerHits parentChildInnerHits = new InnerHitsContext.ParentChildInnerHits(innerHits.v2(), query, null, childDocMapper); - String name = innerHits.v1() != null ? innerHits.v1() : childType; - parseContext.addInnerHits(name, parentChildInnerHits); - } - ParentFieldMapper parentFieldMapper = childDocMapper.parentFieldMapper(); - if (!parentFieldMapper.active()) { - throw new QueryParsingException(parseContext, "Type [" + childType + "] does not have parent mapping"); - } - String parentType = parentFieldMapper.type(); - - // wrap the query with type query - query = new FilteredQuery(query, childDocMapper.typeFilter()); - - DocumentMapper parentDocMapper = parseContext.mapperService().documentMapper(parentType); - if (parentDocMapper == null) { - throw new QueryParsingException(parseContext, "[has_child] Type [" + childType + "] points to a non existent parent type [" - + parentType + "]"); - } - - if (maxChildren > 0 && maxChildren < minChildren) { - throw new QueryParsingException(parseContext, "[has_child] 'max_children' is less than 'min_children'"); - } - - BitDocIdSetFilter nonNestedDocsFilter = null; - if (parentDocMapper.hasNestedObjects()) { - nonNestedDocsFilter = parseContext.bitsetFilter(Queries.newNonNestedFilter()); - } - - Filter parentFilter = parentDocMapper.typeFilter(); - ParentChildIndexFieldData parentChildIndexFieldData = parseContext.getForField(parentFieldMapper); - - Query childrenQuery; - if (minChildren > 1 || maxChildren > 0) { - childrenQuery = new ChildrenQuery(parentChildIndexFieldData, parentType, childType, parentFilter,query,ScoreType.NONE,minChildren, maxChildren, shortCircuitParentDocSet, nonNestedDocsFilter); - } else { - childrenQuery = new ChildrenConstantScoreQuery(parentChildIndexFieldData, query, parentType, childType, parentFilter, - shortCircuitParentDocSet, nonNestedDocsFilter); - } - if (filterName != null) { - parseContext.addNamedFilter(filterName, new QueryWrapperFilter(childrenQuery)); - } - return new QueryWrapperFilter(childrenQuery); - } - -} diff --git a/src/main/java/org/elasticsearch/index/query/HasChildQueryParser.java b/src/main/java/org/elasticsearch/index/query/HasChildQueryParser.java index 2e55395535c..330c99c313e 100644 --- a/src/main/java/org/elasticsearch/index/query/HasChildQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/HasChildQueryParser.java @@ -20,9 +20,10 @@ package org.elasticsearch.index.query; import org.apache.lucene.search.Filter; -import org.apache.lucene.search.FilteredQuery; import org.apache.lucene.search.Query; +import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.join.BitDocIdSetFilter; +import org.elasticsearch.common.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.inject.Inject; @@ -47,6 +48,7 @@ import java.io.IOException; public class HasChildQueryParser implements QueryParser { public static final String NAME = "has_child"; + private static final ParseField QUERY_FIELD = new ParseField("query", "filter"); private final InnerHitsQueryParserHelper innerHitsQueryParserHelper; @@ -80,12 +82,14 @@ public class HasChildQueryParser implements QueryParser { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); + } else if (parseContext.isDeprecatedSetting(currentFieldName)) { + // skip } else if (token == XContentParser.Token.START_OBJECT) { // Usually, the query would be parsed here, but the child // type may not have been extracted yet, so use the // XContentStructure. facade to parse if available, // or delay parsing if not. - if ("query".equals(currentFieldName)) { + if (QUERY_FIELD.match(currentFieldName)) { iq = new XContentStructure.InnerQuery(parseContext, childType == null ? null : new String[] { childType }); queryFound = true; } else if ("inner_hits".equals(currentFieldName)) { @@ -165,10 +169,11 @@ public class HasChildQueryParser implements QueryParser { } // wrap the query with type query - innerQuery = new FilteredQuery(innerQuery, childDocMapper.typeFilter()); + innerQuery = Queries.filtered(innerQuery, childDocMapper.typeFilter()); Query query; - Filter parentFilter = parentDocMapper.typeFilter(); + // TODO: use the query API + Filter parentFilter = new QueryWrapperFilter(parentDocMapper.typeFilter()); ParentChildIndexFieldData parentChildIndexFieldData = parseContext.getForField(parentFieldMapper); if (minChildren > 1 || maxChildren > 0 || scoreType != ScoreType.NONE) { query = new ChildrenQuery(parentChildIndexFieldData, parentType, childType, parentFilter, innerQuery, scoreType, minChildren, diff --git a/src/main/java/org/elasticsearch/index/query/HasParentFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/HasParentFilterBuilder.java deleted file mode 100644 index 8f565022c4f..00000000000 --- a/src/main/java/org/elasticsearch/index/query/HasParentFilterBuilder.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.elasticsearch.index.query; - -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.support.QueryInnerHitBuilder; - -import java.io.IOException; - -/** - * Builder for the 'has_parent' filter. - */ -public class HasParentFilterBuilder extends BaseFilterBuilder { - - private final QueryBuilder queryBuilder; - private final FilterBuilder filterBuilder; - private final String parentType; - private String filterName; - private QueryInnerHitBuilder innerHit = null; - - /** - * @param parentType The parent type - * @param parentQuery The query that will be matched with parent documents - */ - public HasParentFilterBuilder(String parentType, QueryBuilder parentQuery) { - this.parentType = parentType; - this.queryBuilder = parentQuery; - this.filterBuilder = null; - } - - /** - * @param parentType The parent type - * @param parentFilter The filter that will be matched with parent documents - */ - public HasParentFilterBuilder(String parentType, FilterBuilder parentFilter) { - this.parentType = parentType; - this.queryBuilder = null; - this.filterBuilder = parentFilter; - } - - /** - * Sets the filter name for the filter that can be used when searching for matched_filters per hit. - */ - public HasParentFilterBuilder filterName(String filterName) { - this.filterName = filterName; - return this; - } - - /** - * Sets inner hit definition in the scope of this filter and reusing the defined type and query. - */ - public HasParentFilterBuilder innerHit(QueryInnerHitBuilder innerHit) { - this.innerHit = innerHit; - return this; - } - - @Override - protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(HasParentFilterParser.NAME); - if (queryBuilder != null) { - builder.field("query"); - queryBuilder.toXContent(builder, params); - } else if (filterBuilder != null) { - builder.field("filter"); - filterBuilder.toXContent(builder, params); - } - builder.field("parent_type", parentType); - if (filterName != null) { - builder.field("_name", filterName); - } - if (innerHit != null) { - builder.startObject("inner_hits"); - builder.value(innerHit); - builder.endObject(); - } - builder.endObject(); - } -} - diff --git a/src/main/java/org/elasticsearch/index/query/HasParentFilterParser.java b/src/main/java/org/elasticsearch/index/query/HasParentFilterParser.java deleted file mode 100644 index 331f575df77..00000000000 --- a/src/main/java/org/elasticsearch/index/query/HasParentFilterParser.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.elasticsearch.index.query; - -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.Query; -import org.apache.lucene.search.QueryWrapperFilter; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.collect.Tuple; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.query.support.InnerHitsQueryParserHelper; -import org.elasticsearch.index.query.support.XContentStructure; -import org.elasticsearch.search.internal.SubSearchContext; - -import java.io.IOException; - -import static org.elasticsearch.index.query.HasParentQueryParser.createParentQuery; - -/** - * - */ -public class HasParentFilterParser implements FilterParser { - - public static final String NAME = "has_parent"; - - private final InnerHitsQueryParserHelper innerHitsQueryParserHelper; - - @Inject - public HasParentFilterParser(InnerHitsQueryParserHelper innerHitsQueryParserHelper) { - this.innerHitsQueryParserHelper = innerHitsQueryParserHelper; - } - - @Override - public String[] names() { - return new String[]{NAME, Strings.toCamelCase(NAME)}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - boolean queryFound = false; - boolean filterFound = false; - String parentType = null; - Tuple innerHits = null; - - String filterName = null; - String currentFieldName = null; - XContentParser.Token token; - XContentStructure.InnerQuery iq = null; - XContentStructure.InnerFilter innerFilter = null; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (parseContext.isDeprecatedSetting(currentFieldName)) { - // skip - } else if (token == XContentParser.Token.START_OBJECT) { - // Usually, the query would be parsed here, but the child - // type may not have been extracted yet, so use the - // XContentStructure. facade to parse if available, - // or delay parsing if not. - if ("query".equals(currentFieldName)) { - iq = new XContentStructure.InnerQuery(parseContext, parentType == null ? null : new String[] {parentType}); - queryFound = true; - } else if ("filter".equals(currentFieldName)) { - innerFilter = new XContentStructure.InnerFilter(parseContext, parentType == null ? null : new String[] {parentType}); - filterFound = true; - } else if ("inner_hits".equals(currentFieldName)) { - innerHits = innerHitsQueryParserHelper.parse(parseContext); - } else { - throw new QueryParsingException(parseContext, "[has_parent] filter does not support [" + currentFieldName + "]"); - } - } else if (token.isValue()) { - if ("type".equals(currentFieldName) || "parent_type".equals(currentFieldName) || "parentType".equals(currentFieldName)) { - parentType = parser.text(); - } else if ("_name".equals(currentFieldName)) { - filterName = parser.text(); - } else { - throw new QueryParsingException(parseContext, "[has_parent] filter does not support [" + currentFieldName + "]"); - } - } - } - if (!queryFound && !filterFound) { - throw new QueryParsingException(parseContext, "[has_parent] filter requires 'query' or 'filter' field"); - } - if (parentType == null) { - throw new QueryParsingException(parseContext, "[has_parent] filter requires 'parent_type' field"); - } - - Query innerQuery; - if (queryFound) { - innerQuery = iq.asQuery(parentType); - } else { - innerQuery = innerFilter.asFilter(parentType); - } - - if (innerQuery == null) { - return null; - } - - Query parentQuery = createParentQuery(innerQuery, parentType, false, parseContext, innerHits); - if (parentQuery == null) { - return null; - } - if (filterName != null) { - parseContext.addNamedFilter(filterName, new QueryWrapperFilter(parentQuery)); - } - return new QueryWrapperFilter(parentQuery); - } - -} diff --git a/src/main/java/org/elasticsearch/index/query/HasParentQueryParser.java b/src/main/java/org/elasticsearch/index/query/HasParentQueryParser.java index 0d718efdb69..ae85d3230ad 100644 --- a/src/main/java/org/elasticsearch/index/query/HasParentQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/HasParentQueryParser.java @@ -21,9 +21,9 @@ package org.elasticsearch.index.query; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Filter; -import org.apache.lucene.search.FilteredQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.QueryWrapperFilter; +import org.elasticsearch.common.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.inject.Inject; @@ -46,6 +46,7 @@ import java.util.Set; public class HasParentQueryParser implements QueryParser { public static final String NAME = "has_parent"; + private static final ParseField QUERY_FIELD = new ParseField("query", "filter"); private final InnerHitsQueryParserHelper innerHitsQueryParserHelper; @@ -81,7 +82,7 @@ public class HasParentQueryParser implements QueryParser { // type may not have been extracted yet, so use the // XContentStructure. facade to parse if available, // or delay parsing if not. - if ("query".equals(currentFieldName)) { + if (QUERY_FIELD.match(currentFieldName)) { iq = new XContentStructure.InnerQuery(parseContext, parentType == null ? null : new String[] {parentType}); queryFound = true; } else if ("inner_hits".equals(currentFieldName)) { @@ -172,7 +173,7 @@ public class HasParentQueryParser implements QueryParser { throw new QueryParsingException(parseContext, "[has_parent] no _parent field configured"); } - Filter parentFilter = null; + Query parentFilter = null; if (parentTypes.size() == 1) { DocumentMapper documentMapper = parseContext.mapperService().documentMapper(parentTypes.iterator().next()); if (documentMapper != null) { @@ -194,7 +195,7 @@ public class HasParentQueryParser implements QueryParser { } // wrap the query with type query - innerQuery = new FilteredQuery(innerQuery, parentDocMapper.typeFilter()); + innerQuery = Queries.filtered(innerQuery, parentDocMapper.typeFilter()); Filter childrenFilter = new QueryWrapperFilter(Queries.not(parentFilter)); if (score) { return new ParentQuery(parentChildIndexFieldData, innerQuery, parentDocMapper.type(), childrenFilter); diff --git a/src/main/java/org/elasticsearch/index/query/IdsFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/IdsFilterBuilder.java deleted file mode 100644 index 0be091cdc4f..00000000000 --- a/src/main/java/org/elasticsearch/index/query/IdsFilterBuilder.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.common.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * A filter that will return only documents matching specific ids (and a type). - */ -public class IdsFilterBuilder extends BaseFilterBuilder { - - private final List types; - - private List values = new ArrayList<>(); - - private String filterName; - - /** - * Create an ids filter based on the type. - */ - public IdsFilterBuilder(String... types) { - this.types = types == null ? null : Arrays.asList(types); - } - - /** - * Adds ids to the filter. - */ - public IdsFilterBuilder addIds(String... ids) { - values.addAll(Arrays.asList(ids)); - return this; - } - - /** - * Adds ids to the filter. - */ - public IdsFilterBuilder ids(String... ids) { - return addIds(ids); - } - - /** - * Sets the filter name for the filter that can be used when searching for matched_filters per hit. - */ - public IdsFilterBuilder filterName(String filterName) { - this.filterName = filterName; - return this; - } - - @Override - public void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(IdsFilterParser.NAME); - if (types != null) { - if (types.size() == 1) { - builder.field("type", types.get(0)); - } else { - builder.startArray("types"); - for (Object type : types) { - builder.value(type); - } - builder.endArray(); - } - } - builder.startArray("values"); - for (Object value : values) { - builder.value(value); - } - builder.endArray(); - - if (filterName != null) { - builder.field("_name", filterName); - } - - builder.endObject(); - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/IdsFilterParser.java b/src/main/java/org/elasticsearch/index/query/IdsFilterParser.java deleted file mode 100644 index 23d4c9c1483..00000000000 --- a/src/main/java/org/elasticsearch/index/query/IdsFilterParser.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -import org.apache.lucene.queries.TermsQuery; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.QueryWrapperFilter; -import org.apache.lucene.util.BytesRef; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.lucene.search.Queries; -import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.mapper.Uid; -import org.elasticsearch.index.mapper.internal.UidFieldMapper; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -public class IdsFilterParser implements FilterParser { - - public static final String NAME = "ids"; - - @Inject - public IdsFilterParser() { - } - - @Override - public String[] names() { - return new String[]{NAME}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - List ids = new ArrayList<>(); - Collection types = null; - String filterName = null; - String currentFieldName = null; - XContentParser.Token token; - boolean idsProvided = false; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (token == XContentParser.Token.START_ARRAY) { - if ("values".equals(currentFieldName)) { - idsProvided = true; - while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - BytesRef value = parser.utf8BytesOrNull(); - if (value == null) { - throw new QueryParsingException(parseContext, "No value specified for term filter"); - } - ids.add(value); - } - } else if ("types".equals(currentFieldName) || "type".equals(currentFieldName)) { - types = new ArrayList<>(); - while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - String value = parser.textOrNull(); - if (value == null) { - throw new QueryParsingException(parseContext, "No type specified for term filter"); - } - types.add(value); - } - } else { - throw new QueryParsingException(parseContext, "[ids] filter does not support [" + currentFieldName + "]"); - } - } else if (token.isValue()) { - if ("type".equals(currentFieldName) || "_type".equals(currentFieldName)) { - types = ImmutableList.of(parser.text()); - } else if ("_name".equals(currentFieldName)) { - filterName = parser.text(); - } else { - throw new QueryParsingException(parseContext, "[ids] filter does not support [" + currentFieldName + "]"); - } - } - } - - if (!idsProvided) { - throw new QueryParsingException(parseContext, "[ids] filter requires providing a values element"); - } - - if (ids.isEmpty()) { - return Queries.newMatchNoDocsFilter(); - } - - if (types == null || types.isEmpty()) { - types = parseContext.queryTypes(); - } else if (types.size() == 1 && Iterables.getFirst(types, null).equals("_all")) { - types = parseContext.mapperService().types(); - } - - Filter filter = new QueryWrapperFilter(new TermsQuery(UidFieldMapper.NAME, Uid.createTypeUids(types, ids))); - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); - } - return filter; - } -} diff --git a/src/main/java/org/elasticsearch/index/query/IndexQueryParserModule.java b/src/main/java/org/elasticsearch/index/query/IndexQueryParserModule.java index 5f349881071..0953b4f04a6 100644 --- a/src/main/java/org/elasticsearch/index/query/IndexQueryParserModule.java +++ b/src/main/java/org/elasticsearch/index/query/IndexQueryParserModule.java @@ -74,37 +74,6 @@ public class IndexQueryParserModule extends AbstractModule { } } - /** - * Extension point to bind a custom {@link FilterParserFactory}. - */ - public void processXContentFilterParsers(XContentFilterParsersBindings bindings) { - - } - - public static class XContentFilterParsersBindings { - - private final MapBinder binder; - private final Map groupSettings; - - public XContentFilterParsersBindings(MapBinder binder, Map groupSettings) { - this.binder = binder; - this.groupSettings = groupSettings; - } - - public MapBinder binder() { - return binder; - } - - public Map groupSettings() { - return groupSettings; - } - - public void processXContentQueryFilter(String name, Class xcontentFilterParser) { - if (!groupSettings.containsKey(name)) { - binder.addBinding(name).toProvider(FactoryProvider.newFactory(FilterParserFactory.class, xcontentFilterParser)).in(Scopes.SINGLETON); - } - } - } } private final Settings settings; @@ -112,7 +81,6 @@ public class IndexQueryParserModule extends AbstractModule { private final LinkedList processors = Lists.newLinkedList(); private final Map> queries = Maps.newHashMap(); - private final Map> filters = Maps.newHashMap(); public IndexQueryParserModule(Settings settings) { this.settings = settings; @@ -128,16 +96,6 @@ public class IndexQueryParserModule extends AbstractModule { queries.put(name, queryParser); } - /** - * Adds a custom filter parser. - * - * @param name The name of the filter parser - * @param filterParser the class of the filter parser - */ - public void addFilterParser(String name, Class filterParser) { - filters.put(name, filterParser); - } - public IndexQueryParserModule addProcessor(QueryParsersProcessor processor) { processors.addFirst(processor); return this; @@ -172,29 +130,5 @@ public class IndexQueryParserModule extends AbstractModule { for (Map.Entry> entry : queries.entrySet()) { queryBinder.addBinding(entry.getKey()).toProvider(FactoryProvider.newFactory(QueryParserFactory.class, entry.getValue())).in(Scopes.SINGLETON); } - - // handle XContentFilterParsers - MapBinder filterBinder - = MapBinder.newMapBinder(binder(), String.class, FilterParserFactory.class); - Map xContentFilterParserGroups = settings.getGroups(IndexQueryParserService.Defaults.FILTER_PREFIX); - for (Map.Entry entry : xContentFilterParserGroups.entrySet()) { - String fName = entry.getKey(); - Settings fSettings = entry.getValue(); - Class type = fSettings.getAsClass("type", null); - if (type == null) { - throw new IllegalArgumentException("Filter Parser [" + fName + "] must be provided with a type"); - } - filterBinder.addBinding(fName).toProvider(FactoryProvider.newFactory(FilterParserFactory.class, - fSettings.getAsClass("type", null))).in(Scopes.SINGLETON); - } - - QueryParsersProcessor.XContentFilterParsersBindings xContentFilterParsersBindings = new QueryParsersProcessor.XContentFilterParsersBindings(filterBinder, xContentFilterParserGroups); - for (QueryParsersProcessor processor : processors) { - processor.processXContentFilterParsers(xContentFilterParsersBindings); - } - - for (Map.Entry> entry : filters.entrySet()) { - filterBinder.addBinding(entry.getKey()).toProvider(FactoryProvider.newFactory(FilterParserFactory.class, entry.getValue())).in(Scopes.SINGLETON); - } } } diff --git a/src/main/java/org/elasticsearch/index/query/IndexQueryParserService.java b/src/main/java/org/elasticsearch/index/query/IndexQueryParserService.java index 4d04e8e675b..76f46d795b7 100644 --- a/src/main/java/org/elasticsearch/index/query/IndexQueryParserService.java +++ b/src/main/java/org/elasticsearch/index/query/IndexQueryParserService.java @@ -24,7 +24,6 @@ import com.google.common.collect.ImmutableMap; import org.apache.lucene.search.Filter; import org.apache.lucene.search.Query; import org.apache.lucene.util.CloseableThreadLocal; -import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; @@ -95,8 +94,6 @@ public class IndexQueryParserService extends AbstractIndexComponent { private final Map queryParsers; - private final Map filterParsers; - private String defaultField; private boolean queryStringLenient; private final boolean strict; @@ -109,8 +106,7 @@ public class IndexQueryParserService extends AbstractIndexComponent { MapperService mapperService, IndexCache indexCache, IndexFieldDataService fieldDataService, BitsetFilterCache bitsetFilterCache, @Nullable SimilarityService similarityService, - @Nullable Map namedQueryParsers, - @Nullable Map namedFilterParsers) { + @Nullable Map namedQueryParsers) { super(index, indexSettings); this.scriptService = scriptService; this.analysisService = analysisService; @@ -147,29 +143,6 @@ public class IndexQueryParserService extends AbstractIndexComponent { } } this.queryParsers = ImmutableMap.copyOf(queryParsersMap); - - List filterParsers = newArrayList(); - if (namedFilterParsers != null) { - Map filterParserGroups = indexSettings.getGroups(IndexQueryParserService.Defaults.FILTER_PREFIX); - for (Map.Entry entry : namedFilterParsers.entrySet()) { - String filterParserName = entry.getKey(); - FilterParserFactory filterParserFactory = entry.getValue(); - Settings filterParserSettings = filterParserGroups.get(filterParserName); - if (filterParserSettings == null) { - filterParserSettings = EMPTY_SETTINGS; - } - filterParsers.add(filterParserFactory.create(filterParserName, filterParserSettings)); - } - } - - Map filterParsersMap = newHashMap(); - filterParsersMap.putAll(indicesQueriesRegistry.filterParsers()); - if (filterParsers != null) { - for (FilterParser filterParser : filterParsers) { - add(filterParsersMap, filterParser); - } - } - this.filterParsers = ImmutableMap.copyOf(filterParsersMap); } public void close() { @@ -188,10 +161,6 @@ public class IndexQueryParserService extends AbstractIndexComponent { return queryParsers.get(name); } - public FilterParser filterParser(String name) { - return filterParsers.get(name); - } - public ParsedQuery parse(QueryBuilder queryBuilder) { XContentParser parser = null; try { @@ -281,15 +250,15 @@ public class IndexQueryParserService extends AbstractIndexComponent { * Parses an inner filter, returning null if the filter should be ignored. */ @Nullable - public ParsedFilter parseInnerFilter(XContentParser parser) throws IOException { + public ParsedQuery parseInnerFilter(XContentParser parser) throws IOException { QueryParseContext context = cache.get(); context.reset(parser); try { - Filter filter = context.parseInnerFilter(); + Query filter = context.parseInnerFilter(); if (filter == null) { return null; } - return new ParsedFilter(filter, context.copyNamedFilters()); + return new ParsedQuery(filter, context.copyNamedFilters()); } finally { context.reset(null); } @@ -382,12 +351,6 @@ public class IndexQueryParserService extends AbstractIndexComponent { } } - private void add(Map map, FilterParser filterParser) { - for (String name : filterParser.names()) { - map.put(name.intern(), filterParser); - } - } - private void add(Map map, QueryParser queryParser) { for (String name : queryParser.names()) { map.put(name.intern(), queryParser); diff --git a/src/main/java/org/elasticsearch/index/query/IndicesFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/IndicesFilterBuilder.java deleted file mode 100644 index 3ffed450452..00000000000 --- a/src/main/java/org/elasticsearch/index/query/IndicesFilterBuilder.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.common.xcontent.XContentBuilder; - -import java.io.IOException; - -/** - * A filter that will execute the wrapped filter only for the specified indices, and "match_all" when - * it does not match those indices (by default). - */ -public class IndicesFilterBuilder extends BaseFilterBuilder { - - private final FilterBuilder filterBuilder; - - private final String[] indices; - - private String sNoMatchFilter; - private FilterBuilder noMatchFilter; - - private String filterName; - - public IndicesFilterBuilder(FilterBuilder filterBuilder, String... indices) { - this.filterBuilder = filterBuilder; - this.indices = indices; - } - - /** - * Sets the no match filter, can either be all or none. - */ - public IndicesFilterBuilder noMatchFilter(String type) { - this.sNoMatchFilter = type; - return this; - } - - /** - * Sets the filter to use when it executes on an index that does not match the indices provided. - */ - public IndicesFilterBuilder noMatchFilter(FilterBuilder noMatchFilter) { - this.noMatchFilter = noMatchFilter; - return this; - } - - /** - * Sets the filter name for the filter that can be used when searching for matched_filters per hit. - */ - public IndicesFilterBuilder filterName(String filterName) { - this.filterName = filterName; - return this; - } - - @Override - protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(IndicesFilterParser.NAME); - builder.field("indices", indices); - builder.field("filter"); - filterBuilder.toXContent(builder, params); - if (noMatchFilter != null) { - builder.field("no_match_filter"); - noMatchFilter.toXContent(builder, params); - } else if (sNoMatchFilter != null) { - builder.field("no_match_filter", sNoMatchFilter); - } - - if (filterName != null) { - builder.field("_name", filterName); - } - - builder.endObject(); - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/IndicesFilterParser.java b/src/main/java/org/elasticsearch/index/query/IndicesFilterParser.java deleted file mode 100644 index 7bd39dad947..00000000000 --- a/src/main/java/org/elasticsearch/index/query/IndicesFilterParser.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.apache.lucene.search.Filter; -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.cluster.ClusterService; -import org.elasticsearch.common.Nullable; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.lucene.search.Queries; -import org.elasticsearch.common.regex.Regex; -import org.elasticsearch.common.xcontent.XContentParser; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; - -/** - */ -public class IndicesFilterParser implements FilterParser { - - public static final String NAME = "indices"; - - @Nullable - private final ClusterService clusterService; - - @Inject - public IndicesFilterParser(@Nullable ClusterService clusterService) { - this.clusterService = clusterService; - } - - @Override - public String[] names() { - return new String[]{NAME}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - Filter filter = null; - Filter noMatchFilter = Queries.newMatchAllFilter(); - boolean filterFound = false; - boolean indicesFound = false; - boolean currentIndexMatchesIndices = false; - String filterName = null; - - String currentFieldName = null; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (token == XContentParser.Token.START_OBJECT) { - if ("filter".equals(currentFieldName)) { - filterFound = true; - //TODO We are able to decide whether to parse the filter or not only if indices in the query appears first - if (indicesFound && !currentIndexMatchesIndices) { - parseContext.parser().skipChildren(); // skip the filter object without parsing it - } else { - filter = parseContext.parseInnerFilter(); - } - } else if ("no_match_filter".equals(currentFieldName)) { - if (indicesFound && currentIndexMatchesIndices) { - parseContext.parser().skipChildren(); // skip the filter object without parsing it - } else { - noMatchFilter = parseContext.parseInnerFilter(); - } - } else { - throw new QueryParsingException(parseContext, "[indices] filter does not support [" + currentFieldName + "]"); - } - } else if (token == XContentParser.Token.START_ARRAY) { - if ("indices".equals(currentFieldName)) { - if (indicesFound) { - throw new QueryParsingException(parseContext, "[indices] indices or index already specified"); - } - indicesFound = true; - Collection indices = new ArrayList<>(); - while (parser.nextToken() != XContentParser.Token.END_ARRAY) { - String value = parser.textOrNull(); - if (value == null) { - throw new QueryParsingException(parseContext, "[indices] no value specified for 'indices' entry"); - } - indices.add(value); - } - currentIndexMatchesIndices = matchesIndices(parseContext.index().name(), indices.toArray(new String[indices.size()])); - } else { - throw new QueryParsingException(parseContext, "[indices] filter does not support [" + currentFieldName + "]"); - } - } else if (token.isValue()) { - if ("index".equals(currentFieldName)) { - if (indicesFound) { - throw new QueryParsingException(parseContext, "[indices] indices or index already specified"); - } - indicesFound = true; - currentIndexMatchesIndices = matchesIndices(parseContext.index().name(), parser.text()); - } else if ("no_match_filter".equals(currentFieldName)) { - String type = parser.text(); - if ("all".equals(type)) { - noMatchFilter = Queries.newMatchAllFilter(); - } else if ("none".equals(type)) { - noMatchFilter = Queries.newMatchNoDocsFilter(); - } - } else if ("_name".equals(currentFieldName)) { - filterName = parser.text(); - } else { - throw new QueryParsingException(parseContext, "[indices] filter does not support [" + currentFieldName + "]"); - } - } - } - if (!filterFound) { - throw new QueryParsingException(parseContext, "[indices] requires 'filter' element"); - } - if (!indicesFound) { - throw new QueryParsingException(parseContext, "[indices] requires 'indices' or 'index' element"); - } - - Filter chosenFilter; - if (currentIndexMatchesIndices) { - chosenFilter = filter; - } else { - chosenFilter = noMatchFilter; - } - - if (filterName != null) { - parseContext.addNamedFilter(filterName, chosenFilter); - } - - return chosenFilter; - } - - protected boolean matchesIndices(String currentIndex, String... indices) { - final String[] concreteIndices = clusterService.state().metaData().concreteIndices(IndicesOptions.lenientExpandOpen(), indices); - for (String index : concreteIndices) { - if (Regex.simpleMatch(index, currentIndex)) { - return true; - } - } - return false; - } -} diff --git a/src/main/java/org/elasticsearch/index/query/IndicesQueryParser.java b/src/main/java/org/elasticsearch/index/query/IndicesQueryParser.java index a45fe9f88f6..db5662644c4 100644 --- a/src/main/java/org/elasticsearch/index/query/IndicesQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/IndicesQueryParser.java @@ -23,6 +23,7 @@ import org.apache.lucene.search.Query; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.common.Nullable; +import org.elasticsearch.common.ParseField; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.regex.Regex; @@ -38,6 +39,8 @@ import java.util.Collection; public class IndicesQueryParser implements QueryParser { public static final String NAME = "indices"; + private static final ParseField QUERY_FIELD = new ParseField("query", "filter"); + private static final ParseField NO_MATCH_QUERY = new ParseField("no_match_query", "no_match_filter"); @Nullable private final ClusterService clusterService; @@ -70,10 +73,10 @@ public class IndicesQueryParser implements QueryParser { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { - if ("query".equals(currentFieldName)) { + if (QUERY_FIELD.match(currentFieldName)) { innerQuery = new XContentStructure.InnerQuery(parseContext, null); queryFound = true; - } else if ("no_match_query".equals(currentFieldName)) { + } else if (NO_MATCH_QUERY.match(currentFieldName)) { innerNoMatchQuery = new XContentStructure.InnerQuery(parseContext, null); } else { throw new QueryParsingException(parseContext, "[indices] query does not support [" + currentFieldName + "]"); @@ -103,7 +106,7 @@ public class IndicesQueryParser implements QueryParser { } indicesFound = true; currentIndexMatchesIndices = matchesIndices(parseContext.index().name(), parser.text()); - } else if ("no_match_query".equals(currentFieldName)) { + } else if (NO_MATCH_QUERY.match(currentFieldName)) { String type = parser.text(); if ("all".equals(type)) { noMatchQuery = Queries.newMatchAllQuery(); diff --git a/src/main/java/org/elasticsearch/index/query/LimitFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/LimitQueryBuilder.java similarity index 89% rename from src/main/java/org/elasticsearch/index/query/LimitFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/LimitQueryBuilder.java index 552c47b6cf6..23497429581 100644 --- a/src/main/java/org/elasticsearch/index/query/LimitFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/LimitQueryBuilder.java @@ -28,17 +28,17 @@ import java.io.IOException; * @deprecated Use {@link SearchRequestBuilder#setTerminateAfter(int)} instead. */ @Deprecated -public class LimitFilterBuilder extends BaseFilterBuilder { +public class LimitQueryBuilder extends BaseQueryBuilder { private final int limit; - public LimitFilterBuilder(int limit) { + public LimitQueryBuilder(int limit) { this.limit = limit; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(LimitFilterParser.NAME); + builder.startObject(LimitQueryParser.NAME); builder.field("value", limit); builder.endObject(); } diff --git a/src/main/java/org/elasticsearch/index/query/LimitFilterParser.java b/src/main/java/org/elasticsearch/index/query/LimitQueryParser.java similarity index 84% rename from src/main/java/org/elasticsearch/index/query/LimitFilterParser.java rename to src/main/java/org/elasticsearch/index/query/LimitQueryParser.java index f4f8fde7427..3419f6146a7 100644 --- a/src/main/java/org/elasticsearch/index/query/LimitFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/LimitQueryParser.java @@ -19,19 +19,20 @@ package org.elasticsearch.index.query; -import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; -public class LimitFilterParser implements FilterParser { +@Deprecated +public class LimitQueryParser implements QueryParser { public static final String NAME = "limit"; @Inject - public LimitFilterParser() { + public LimitQueryParser() { } @Override @@ -40,7 +41,7 @@ public class LimitFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); int limit = -1; @@ -53,16 +54,16 @@ public class LimitFilterParser implements FilterParser { if ("value".equals(currentFieldName)) { limit = parser.intValue(); } else { - throw new QueryParsingException(parseContext, "[limit] filter does not support [" + currentFieldName + "]"); + throw new QueryParsingException(parseContext, "[limit] query does not support [" + currentFieldName + "]"); } } } if (limit == -1) { - throw new QueryParsingException(parseContext, "No value specified for limit filter"); + throw new QueryParsingException(parseContext, "No value specified for limit query"); } // this filter is deprecated and parses to a filter that matches everything - return Queries.newMatchAllFilter(); + return Queries.newMatchAllQuery(); } } diff --git a/src/main/java/org/elasticsearch/index/query/MatchAllFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/MatchAllFilterBuilder.java deleted file mode 100644 index ebb4ffd9fd3..00000000000 --- a/src/main/java/org/elasticsearch/index/query/MatchAllFilterBuilder.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.common.xcontent.XContentBuilder; - -import java.io.IOException; - -/** - * A filter that simply wraps a query. - * - * - */ -public class MatchAllFilterBuilder extends BaseFilterBuilder { - - /** - * A filter that simply matches all docs. - */ - public MatchAllFilterBuilder() { - } - - @Override - protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(MatchAllFilterParser.NAME).endObject(); - } -} diff --git a/src/main/java/org/elasticsearch/index/query/MatchAllFilterParser.java b/src/main/java/org/elasticsearch/index/query/MatchAllFilterParser.java deleted file mode 100644 index 2d78edad685..00000000000 --- a/src/main/java/org/elasticsearch/index/query/MatchAllFilterParser.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.apache.lucene.search.Filter; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.lucene.search.Queries; -import org.elasticsearch.common.xcontent.XContentParser; - -import java.io.IOException; - -/** - * - */ -public class MatchAllFilterParser implements FilterParser { - - public static final String NAME = "match_all"; - - @Inject - public MatchAllFilterParser() { - } - - @Override - public String[] names() { - return new String[]{NAME, Strings.toCamelCase(NAME)}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - XContentParser.Token token; - while (((token = parser.nextToken()) != XContentParser.Token.END_OBJECT && token != XContentParser.Token.END_ARRAY)) { - } - - return Queries.newMatchAllFilter(); - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/MissingFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/MissingQueryBuilder.java similarity index 80% rename from src/main/java/org/elasticsearch/index/query/MissingFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/MissingQueryBuilder.java index 68e2eba2626..b01b8817d55 100644 --- a/src/main/java/org/elasticsearch/index/query/MissingFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/MissingQueryBuilder.java @@ -26,17 +26,17 @@ import java.io.IOException; /** * Constructs a filter that only match on documents that the field has a value in them. */ -public class MissingFilterBuilder extends BaseFilterBuilder { +public class MissingQueryBuilder extends BaseQueryBuilder { private String name; - private String filterName; + private String queryName; private Boolean nullValue; private Boolean existence; - public MissingFilterBuilder(String name) { + public MissingQueryBuilder(String name) { this.name = name; } @@ -44,7 +44,7 @@ public class MissingFilterBuilder extends BaseFilterBuilder { * Should the missing filter automatically include fields with null value configured in the * mappings. Defaults to false. */ - public MissingFilterBuilder nullValue(boolean nullValue) { + public MissingQueryBuilder nullValue(boolean nullValue) { this.nullValue = nullValue; return this; } @@ -53,7 +53,7 @@ public class MissingFilterBuilder extends BaseFilterBuilder { * Should the missing filter include documents where the field doesn't exists in the docs. * Defaults to true. */ - public MissingFilterBuilder existence(boolean existence) { + public MissingQueryBuilder existence(boolean existence) { this.existence = existence; return this; } @@ -61,14 +61,14 @@ public class MissingFilterBuilder extends BaseFilterBuilder { /** * Sets the filter name for the filter that can be used when searching for matched_filters per hit. */ - public MissingFilterBuilder filterName(String filterName) { - this.filterName = filterName; + public MissingQueryBuilder queryName(String queryName) { + this.queryName = queryName; return this; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(MissingFilterParser.NAME); + builder.startObject(MissingQueryParser.NAME); builder.field("field", name); if (nullValue != null) { builder.field("null_value", nullValue); @@ -76,8 +76,8 @@ public class MissingFilterBuilder extends BaseFilterBuilder { if (existence != null) { builder.field("existence", existence); } - if (filterName != null) { - builder.field("_name", filterName); + if (queryName != null) { + builder.field("_name", queryName); } builder.endObject(); } diff --git a/src/main/java/org/elasticsearch/index/query/MissingFilterParser.java b/src/main/java/org/elasticsearch/index/query/MissingQueryParser.java similarity index 84% rename from src/main/java/org/elasticsearch/index/query/MissingFilterParser.java rename to src/main/java/org/elasticsearch/index/query/MissingQueryParser.java index 07af9717dc1..d33d686fb0b 100644 --- a/src/main/java/org/elasticsearch/index/query/MissingFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/MissingQueryParser.java @@ -21,12 +21,12 @@ package org.elasticsearch.index.query; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; +import org.apache.lucene.search.ConstantScoreQuery; import org.apache.lucene.search.Filter; import org.apache.lucene.search.Query; import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.TermRangeQuery; import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.lucene.HashedBytesRef; import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.mapper.FieldMappers; @@ -39,14 +39,14 @@ import java.util.List; /** * */ -public class MissingFilterParser implements FilterParser { +public class MissingQueryParser implements QueryParser { public static final String NAME = "missing"; public static final boolean DEFAULT_NULL_VALUE = false; public static final boolean DEFAULT_EXISTENCE_VALUE = true; @Inject - public MissingFilterParser() { + public MissingQueryParser() { } @Override @@ -55,11 +55,11 @@ public class MissingFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); String fieldPattern = null; - String filterName = null; + String queryName = null; boolean nullValue = DEFAULT_NULL_VALUE; boolean existence = DEFAULT_EXISTENCE_VALUE; @@ -76,9 +76,9 @@ public class MissingFilterParser implements FilterParser { } else if ("existence".equals(currentFieldName)) { existence = parser.booleanValue(); } else if ("_name".equals(currentFieldName)) { - filterName = parser.text(); + queryName = parser.text(); } else { - throw new QueryParsingException(parseContext, "[missing] filter does not support [" + currentFieldName + "]"); + throw new QueryParsingException(parseContext, "[missing] query does not support [" + currentFieldName + "]"); } } } @@ -87,10 +87,10 @@ public class MissingFilterParser implements FilterParser { throw new QueryParsingException(parseContext, "missing must be provided with a [field]"); } - return newFilter(parseContext, fieldPattern, existence, nullValue, filterName); + return newFilter(parseContext, fieldPattern, existence, nullValue, queryName); } - public static Filter newFilter(QueryParseContext parseContext, String fieldPattern, boolean existence, boolean nullValue, String filterName) { + public static Query newFilter(QueryParseContext parseContext, String fieldPattern, boolean existence, boolean nullValue, String queryName) { if (!existence && !nullValue) { throw new QueryParsingException(parseContext, "missing must have either existence, or null_value, or both set to true"); } @@ -107,23 +107,18 @@ public class MissingFilterParser implements FilterParser { if (fields.isEmpty()) { if (existence) { // if we ask for existence of fields, and we found none, then we should match on all - return Queries.newMatchAllFilter(); + return Queries.newMatchAllQuery(); } return null; } Filter existenceFilter = null; - Filter nullFilter = null; - - MapperService.SmartNameFieldMappers nonNullFieldMappers = null; + Query nullFilter = null; if (existence) { BooleanQuery boolFilter = new BooleanQuery(); for (String field : fields) { MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(field); - if (smartNameFieldMappers != null) { - nonNullFieldMappers = smartNameFieldMappers; - } Query filter = null; if (fieldNamesMapper != null && fieldNamesMapper.enabled()) { final String f; @@ -132,11 +127,11 @@ public class MissingFilterParser implements FilterParser { } else { f = field; } - filter = fieldNamesMapper.termFilter(f, parseContext); + filter = fieldNamesMapper.termQuery(f, parseContext); } // if _field_names are not indexed, we need to go the slow way if (filter == null && smartNameFieldMappers != null && smartNameFieldMappers.hasMapper()) { - filter = smartNameFieldMappers.mapper().rangeFilter(null, null, true, true, parseContext); + filter = smartNameFieldMappers.mapper().rangeQuery(null, null, true, true, parseContext); } if (filter == null) { filter = new TermRangeQuery(field, null, null, true, true); @@ -157,14 +152,14 @@ public class MissingFilterParser implements FilterParser { } } - Filter filter; + Query filter; if (nullFilter != null) { if (existenceFilter != null) { BooleanQuery combined = new BooleanQuery(); combined.add(existenceFilter, BooleanClause.Occur.SHOULD); combined.add(nullFilter, BooleanClause.Occur.SHOULD); // cache the not filter as well, so it will be faster - filter = new QueryWrapperFilter(combined); + filter = combined; } else { filter = nullFilter; } @@ -176,9 +171,9 @@ public class MissingFilterParser implements FilterParser { return null; } - if (filterName != null) { - parseContext.addNamedFilter(filterName, existenceFilter); + if (queryName != null) { + parseContext.addNamedQuery(queryName, existenceFilter); } - return filter; + return new ConstantScoreQuery(filter); } } diff --git a/src/main/java/org/elasticsearch/index/query/NestedFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/NestedFilterBuilder.java deleted file mode 100644 index c64c7ef327e..00000000000 --- a/src/main/java/org/elasticsearch/index/query/NestedFilterBuilder.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.support.QueryInnerHitBuilder; - -import java.io.IOException; - -public class NestedFilterBuilder extends BaseFilterBuilder { - - private final QueryBuilder queryBuilder; - private final FilterBuilder filterBuilder; - - private final String path; - private Boolean join; - - private String filterName; - - private QueryInnerHitBuilder innerHit = null; - - public NestedFilterBuilder(String path, QueryBuilder queryBuilder) { - this.path = path; - this.queryBuilder = queryBuilder; - this.filterBuilder = null; - } - - public NestedFilterBuilder(String path, FilterBuilder filterBuilder) { - this.path = path; - this.queryBuilder = null; - this.filterBuilder = filterBuilder; - } - - public NestedFilterBuilder join(boolean join) { - this.join = join; - return this; - } - - /** - * Sets the filter name for the filter that can be used when searching for matched_filters per hit. - */ - public NestedFilterBuilder filterName(String filterName) { - this.filterName = filterName; - return this; - } - - /** - * Sets inner hit definition in the scope of this nested filter and reusing the defined path and query. - */ - public NestedFilterBuilder innerHit(QueryInnerHitBuilder innerHit) { - this.innerHit = innerHit; - return this; - } - - @Override - protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(NestedFilterParser.NAME); - if (queryBuilder != null) { - builder.field("query"); - queryBuilder.toXContent(builder, params); - } else { - builder.field("filter"); - filterBuilder.toXContent(builder, params); - } - if (join != null) { - builder.field("join", join); - } - builder.field("path", path); - if (filterName != null) { - builder.field("_name", filterName); - } - if (innerHit != null) { - builder.startObject("inner_hits"); - builder.value(innerHit); - builder.endObject(); - } - builder.endObject(); - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/NestedFilterParser.java b/src/main/java/org/elasticsearch/index/query/NestedFilterParser.java deleted file mode 100644 index 467705afca7..00000000000 --- a/src/main/java/org/elasticsearch/index/query/NestedFilterParser.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.QueryWrapperFilter; -import org.apache.lucene.search.join.ScoreMode; -import org.apache.lucene.search.join.ToParentBlockJoinQuery; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.query.support.InnerHitsQueryParserHelper; - -import java.io.IOException; - -public class NestedFilterParser implements FilterParser { - - public static final String NAME = "nested"; - - private final InnerHitsQueryParserHelper innerHitsQueryParserHelper; - - @Inject - public NestedFilterParser(InnerHitsQueryParserHelper innerHitsQueryParserHelper) { - this.innerHitsQueryParserHelper = innerHitsQueryParserHelper; - } - - @Override - public String[] names() { - return new String[]{NAME, Strings.toCamelCase(NAME)}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - final NestedQueryParser.ToBlockJoinQueryBuilder builder = new NestedQueryParser.ToBlockJoinQueryBuilder(parseContext); - - float boost = 1.0f; - String filterName = null; - - String currentFieldName = null; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (parseContext.isDeprecatedSetting(currentFieldName)) { - // skip - } else if (token == XContentParser.Token.START_OBJECT) { - if ("query".equals(currentFieldName)) { - builder.query(); - } else if ("filter".equals(currentFieldName)) { - builder.filter(); - } else if ("inner_hits".equals(currentFieldName)) { - builder.setInnerHits(innerHitsQueryParserHelper.parse(parseContext)); - } else { - throw new QueryParsingException(parseContext, "[nested] filter does not support [" + currentFieldName + "]"); - } - } else if (token.isValue()) { - if ("path".equals(currentFieldName)) { - builder.setPath(parser.text()); - } else if ("boost".equals(currentFieldName)) { - boost = parser.floatValue(); - } else if ("_name".equals(currentFieldName)) { - filterName = parser.text(); - } else { - throw new QueryParsingException(parseContext, "[nested] filter does not support [" + currentFieldName + "]"); - } - } - } - builder.setScoreMode(ScoreMode.None); - ToParentBlockJoinQuery joinQuery = builder.build(); - if (joinQuery != null) { - joinQuery.getChildQuery().setBoost(boost); - Filter nestedFilter = new QueryWrapperFilter(joinQuery); - if (filterName != null) { - parseContext.addNamedFilter(filterName, nestedFilter); - } - return nestedFilter; - } else { - return null; - } - } -} diff --git a/src/main/java/org/elasticsearch/index/query/NestedQueryBuilder.java b/src/main/java/org/elasticsearch/index/query/NestedQueryBuilder.java index bd36fa9606e..d82dde7f891 100644 --- a/src/main/java/org/elasticsearch/index/query/NestedQueryBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/NestedQueryBuilder.java @@ -23,11 +23,11 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.support.QueryInnerHitBuilder; import java.io.IOException; +import java.util.Objects; public class NestedQueryBuilder extends BaseQueryBuilder implements BoostableQueryBuilder { private final QueryBuilder queryBuilder; - private final FilterBuilder filterBuilder; private final String path; @@ -41,16 +41,8 @@ public class NestedQueryBuilder extends BaseQueryBuilder implements BoostableQue public NestedQueryBuilder(String path, QueryBuilder queryBuilder) { this.path = path; - this.queryBuilder = queryBuilder; - this.filterBuilder = null; + this.queryBuilder = Objects.requireNonNull(queryBuilder); } - - public NestedQueryBuilder(String path, FilterBuilder filterBuilder) { - this.path = path; - this.queryBuilder = null; - this.filterBuilder = filterBuilder; - } - /** * The score mode. */ @@ -88,13 +80,8 @@ public class NestedQueryBuilder extends BaseQueryBuilder implements BoostableQue @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(NestedQueryParser.NAME); - if (queryBuilder != null) { - builder.field("query"); - queryBuilder.toXContent(builder, params); - } else { - builder.field("filter"); - filterBuilder.toXContent(builder, params); - } + builder.field("query"); + queryBuilder.toXContent(builder, params); builder.field("path", path); if (scoreMode != null) { builder.field("score_mode", scoreMode); diff --git a/src/main/java/org/elasticsearch/index/query/NestedQueryParser.java b/src/main/java/org/elasticsearch/index/query/NestedQueryParser.java index ba9bcf07d46..4af59e8b483 100644 --- a/src/main/java/org/elasticsearch/index/query/NestedQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/NestedQueryParser.java @@ -20,12 +20,12 @@ package org.elasticsearch.index.query; import org.apache.lucene.search.ConstantScoreQuery; -import org.apache.lucene.search.Filter; import org.apache.lucene.search.FilteredQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.join.ScoreMode; import org.apache.lucene.search.join.ToParentBlockJoinQuery; import org.elasticsearch.common.Nullable; +import org.elasticsearch.common.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.inject.Inject; @@ -40,6 +40,7 @@ import java.io.IOException; public class NestedQueryParser implements QueryParser { public static final String NAME = "nested"; + private static final ParseField FILTER_FIELD = new ParseField("filter").withAllDeprecated("query"); private final InnerHitsQueryParserHelper innerHitsQueryParserHelper; @@ -70,7 +71,7 @@ public class NestedQueryParser implements QueryParser { } else if (token == XContentParser.Token.START_OBJECT) { if ("query".equals(currentFieldName)) { builder.query(); - } else if ("filter".equals(currentFieldName)) { + } else if (FILTER_FIELD.match(currentFieldName)) { builder.filter(); } else if ("inner_hits".equals(currentFieldName)) { builder.setInnerHits(innerHitsQueryParserHelper.parse(parseContext)); @@ -137,7 +138,7 @@ public class NestedQueryParser implements QueryParser { if (queryFound) { innerQuery = getInnerQuery(); } else if (filterFound) { - Filter innerFilter = getInnerFilter(); + Query innerFilter = getInnerFilter(); if (innerFilter != null) { innerQuery = new ConstantScoreQuery(getInnerFilter()); } else { diff --git a/src/main/java/org/elasticsearch/index/query/NotFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/NotQueryBuilder.java similarity index 70% rename from src/main/java/org/elasticsearch/index/query/NotFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/NotQueryBuilder.java index 1c5ea06f077..4545c7ae7d5 100644 --- a/src/main/java/org/elasticsearch/index/query/NotFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/NotQueryBuilder.java @@ -22,34 +22,35 @@ package org.elasticsearch.index.query; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; +import java.util.Objects; /** * A filter that matches documents matching boolean combinations of other filters. * * */ -public class NotFilterBuilder extends BaseFilterBuilder { +public class NotQueryBuilder extends BaseQueryBuilder { - private FilterBuilder filter; + private final QueryBuilder filter; - private String filterName; + private String queryName; - public NotFilterBuilder(FilterBuilder filter) { - this.filter = filter; + public NotQueryBuilder(QueryBuilder filter) { + this.filter = Objects.requireNonNull(filter); } - public NotFilterBuilder filterName(String filterName) { - this.filterName = filterName; + public NotQueryBuilder queryName(String queryName) { + this.queryName = queryName; return this; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(NotFilterParser.NAME); - builder.field("filter"); + builder.startObject(NotQueryParser.NAME); + builder.field("query"); filter.toXContent(builder, params); - if (filterName != null) { - builder.field("_name", filterName); + if (queryName != null) { + builder.field("_name", queryName); } builder.endObject(); } diff --git a/src/main/java/org/elasticsearch/index/query/NotFilterParser.java b/src/main/java/org/elasticsearch/index/query/NotQueryParser.java similarity index 65% rename from src/main/java/org/elasticsearch/index/query/NotFilterParser.java rename to src/main/java/org/elasticsearch/index/query/NotQueryParser.java index 7ebf0fe82dc..c5628d49da8 100644 --- a/src/main/java/org/elasticsearch/index/query/NotFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/NotQueryParser.java @@ -19,8 +19,8 @@ package org.elasticsearch.index.query; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.QueryWrapperFilter; +import org.apache.lucene.search.Query; +import org.elasticsearch.common.ParseField; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.xcontent.XContentParser; @@ -30,12 +30,13 @@ import java.io.IOException; /** * */ -public class NotFilterParser implements FilterParser { +public class NotQueryParser implements QueryParser { public static final String NAME = "not"; + private static final ParseField QUERY_FIELD = new ParseField("filter", "query"); @Inject - public NotFilterParser() { + public NotQueryParser() { } @Override @@ -44,13 +45,13 @@ public class NotFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); - Filter filter = null; - boolean filterFound = false; + Query query = null; + boolean queryFound = false; - String filterName = null; + String queryName = null; String currentFieldName = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { @@ -59,39 +60,39 @@ public class NotFilterParser implements FilterParser { } else if (parseContext.isDeprecatedSetting(currentFieldName)) { // skip } else if (token == XContentParser.Token.START_OBJECT) { - if ("filter".equals(currentFieldName)) { - filter = parseContext.parseInnerFilter(); - filterFound = true; + if (QUERY_FIELD.match(currentFieldName)) { + query = parseContext.parseInnerFilter(); + queryFound = true; } else { - filterFound = true; + queryFound = true; // its the filter, and the name is the field - filter = parseContext.parseInnerFilter(currentFieldName); + query = parseContext.parseInnerFilter(currentFieldName); } } else if (token == XContentParser.Token.START_ARRAY) { - filterFound = true; + queryFound = true; // its the filter, and the name is the field - filter = parseContext.parseInnerFilter(currentFieldName); + query = parseContext.parseInnerFilter(currentFieldName); } else if (token.isValue()) { if ("_name".equals(currentFieldName)) { - filterName = parser.text(); + queryName = parser.text(); } else { - throw new QueryParsingException(parseContext, "[not] filter does not support [" + currentFieldName + "]"); + throw new QueryParsingException(parseContext, "[not] query does not support [" + currentFieldName + "]"); } } } - if (!filterFound) { - throw new QueryParsingException(parseContext, "filter is required when using `not` filter"); + if (!queryFound) { + throw new QueryParsingException(parseContext, "filter is required when using `not` query"); } - if (filter == null) { + if (query == null) { return null; } - Filter notFilter = new QueryWrapperFilter(Queries.not(filter)); - if (filterName != null) { - parseContext.addNamedFilter(filterName, notFilter); + Query notQuery = Queries.not(query); + if (queryName != null) { + parseContext.addNamedQuery(queryName, notQuery); } - return notFilter; + return notQuery; } } \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/OrFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/OrQueryBuilder.java similarity index 70% rename from src/main/java/org/elasticsearch/index/query/OrFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/OrQueryBuilder.java index 2feca66fc56..df05973ab8a 100644 --- a/src/main/java/org/elasticsearch/index/query/OrFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/OrQueryBuilder.java @@ -27,17 +27,17 @@ import java.util.ArrayList; /** * A filter that matches documents matching boolean combinations of other filters. - * @deprecated Use {@link BoolFilterBuilder} instead + * @deprecated Use {@link BoolQueryBuilder} instead */ @Deprecated -public class OrFilterBuilder extends BaseFilterBuilder { +public class OrQueryBuilder extends BaseQueryBuilder { - private ArrayList filters = Lists.newArrayList(); + private ArrayList filters = Lists.newArrayList(); - private String filterName; + private String queryName; - public OrFilterBuilder(FilterBuilder... filters) { - for (FilterBuilder filter : filters) { + public OrQueryBuilder(QueryBuilder... filters) { + for (QueryBuilder filter : filters) { this.filters.add(filter); } } @@ -45,26 +45,26 @@ public class OrFilterBuilder extends BaseFilterBuilder { /** * Adds a filter to the list of filters to "or". */ - public OrFilterBuilder add(FilterBuilder filterBuilder) { + public OrQueryBuilder add(QueryBuilder filterBuilder) { filters.add(filterBuilder); return this; } - public OrFilterBuilder filterName(String filterName) { - this.filterName = filterName; + public OrQueryBuilder queryName(String queryName) { + this.queryName = queryName; return this; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(OrFilterParser.NAME); + builder.startObject(OrQueryParser.NAME); builder.startArray("filters"); - for (FilterBuilder filter : filters) { + for (QueryBuilder filter : filters) { filter.toXContent(builder, params); } builder.endArray(); - if (filterName != null) { - builder.field("_name", filterName); + if (queryName != null) { + builder.field("_name", queryName); } builder.endObject(); } diff --git a/src/main/java/org/elasticsearch/index/query/OrFilterParser.java b/src/main/java/org/elasticsearch/index/query/OrQueryParser.java similarity index 66% rename from src/main/java/org/elasticsearch/index/query/OrFilterParser.java rename to src/main/java/org/elasticsearch/index/query/OrQueryParser.java index dae526563c6..acc55e5f428 100644 --- a/src/main/java/org/elasticsearch/index/query/OrFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/OrQueryParser.java @@ -21,8 +21,7 @@ package org.elasticsearch.index.query; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.QueryWrapperFilter; +import org.apache.lucene.search.Query; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentParser; @@ -34,12 +33,13 @@ import static com.google.common.collect.Lists.newArrayList; /** * */ -public class OrFilterParser implements FilterParser { +@Deprecated +public class OrQueryParser implements QueryParser { public static final String NAME = "or"; @Inject - public OrFilterParser() { + public OrQueryParser() { } @Override @@ -48,21 +48,21 @@ public class OrFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); - ArrayList filters = newArrayList(); - boolean filtersFound = false; + ArrayList queries = newArrayList(); + boolean queriesFound = false; - String filterName = null; + String queryName = null; String currentFieldName = null; XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.START_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - filtersFound = true; - Filter filter = parseContext.parseInnerFilter(); + queriesFound = true; + Query filter = parseContext.parseInnerFilter(); if (filter != null) { - filters.add(filter); + queries.add(filter); } } } else { @@ -71,49 +71,47 @@ public class OrFilterParser implements FilterParser { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { if ("filters".equals(currentFieldName)) { - filtersFound = true; + queriesFound = true; while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - Filter filter = parseContext.parseInnerFilter(); + Query filter = parseContext.parseInnerFilter(); if (filter != null) { - filters.add(filter); + queries.add(filter); } } } else { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - filtersFound = true; - Filter filter = parseContext.parseInnerFilter(); + queriesFound = true; + Query filter = parseContext.parseInnerFilter(); if (filter != null) { - filters.add(filter); + queries.add(filter); } } } } else if (token.isValue()) { if ("_name".equals(currentFieldName)) { - filterName = parser.text(); + queryName = parser.text(); } else { - throw new QueryParsingException(parseContext, "[or] filter does not support [" + currentFieldName + "]"); + throw new QueryParsingException(parseContext, "[or] query does not support [" + currentFieldName + "]"); } } } } - if (!filtersFound) { - throw new QueryParsingException(parseContext, "[or] filter requires 'filters' to be set on it'"); + if (!queriesFound) { + throw new QueryParsingException(parseContext, "[or] query requires 'filters' to be set on it'"); } - if (filters.isEmpty()) { + if (queries.isEmpty()) { return null; } - // no need to cache this one - BooleanQuery boolQuery = new BooleanQuery(); - for (Filter filter : filters) { - boolQuery.add(filter, Occur.SHOULD); + BooleanQuery query = new BooleanQuery(); + for (Query f : queries) { + query.add(f, Occur.SHOULD); } - Filter filter = new QueryWrapperFilter(boolQuery); - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); + if (queryName != null) { + parseContext.addNamedQuery(queryName, query); } - return filter; + return query; } } \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/ParsedFilter.java b/src/main/java/org/elasticsearch/index/query/ParsedFilter.java deleted file mode 100644 index abd9280f220..00000000000 --- a/src/main/java/org/elasticsearch/index/query/ParsedFilter.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import com.google.common.collect.ImmutableMap; -import org.apache.lucene.search.Filter; - -public class ParsedFilter { - - private final Filter filter; - private final ImmutableMap namedFilters; - - public ParsedFilter(Filter filter, ImmutableMap namedFilters) { - assert filter != null; - assert namedFilters != null; - this.filter = filter; - this.namedFilters = namedFilters; - } - - public Filter filter() { - return filter; - } - - public ImmutableMap namedFilters() { - return namedFilters; - } -} diff --git a/src/main/java/org/elasticsearch/index/query/ParsedQuery.java b/src/main/java/org/elasticsearch/index/query/ParsedQuery.java index 0ffc4efb696..d1a4ca5ab1c 100644 --- a/src/main/java/org/elasticsearch/index/query/ParsedQuery.java +++ b/src/main/java/org/elasticsearch/index/query/ParsedQuery.java @@ -20,7 +20,7 @@ package org.elasticsearch.index.query; import com.google.common.collect.ImmutableMap; -import org.apache.lucene.search.Filter; + import org.apache.lucene.search.Query; import org.elasticsearch.common.lucene.search.Queries; @@ -32,9 +32,9 @@ import org.elasticsearch.common.lucene.search.Queries; public class ParsedQuery { private final Query query; - private final ImmutableMap namedFilters; + private final ImmutableMap namedFilters; - public ParsedQuery(Query query, ImmutableMap namedFilters) { + public ParsedQuery(Query query, ImmutableMap namedFilters) { this.query = query; this.namedFilters = namedFilters; } @@ -56,11 +56,11 @@ public class ParsedQuery { return this.query; } - public ImmutableMap namedFilters() { + public ImmutableMap namedFilters() { return this.namedFilters; } public static ParsedQuery parsedMatchAllQuery() { - return new ParsedQuery(Queries.newMatchAllQuery(), ImmutableMap.of()); + return new ParsedQuery(Queries.newMatchAllQuery(), ImmutableMap.of()); } } diff --git a/src/main/java/org/elasticsearch/index/query/PrefixFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/PrefixFilterBuilder.java deleted file mode 100644 index d202fcc281f..00000000000 --- a/src/main/java/org/elasticsearch/index/query/PrefixFilterBuilder.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.common.xcontent.XContentBuilder; - -import java.io.IOException; - -/** - * A filter that restricts search results to values that have a matching prefix in a given - * field. - * - * - */ -public class PrefixFilterBuilder extends BaseFilterBuilder { - - private final String name; - - private final String prefix; - - private String filterName; - - /** - * A filter that restricts search results to values that have a matching prefix in a given - * field. - * - * @param name The field name - * @param prefix The prefix - */ - public PrefixFilterBuilder(String name, String prefix) { - this.name = name; - this.prefix = prefix; - } - - /** - * Sets the filter name for the filter that can be used when searching for matched_filters per hit. - */ - public PrefixFilterBuilder filterName(String filterName) { - this.filterName = filterName; - return this; - } - - @Override - public void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(PrefixFilterParser.NAME); - builder.field(name, prefix); - if (filterName != null) { - builder.field("_name", filterName); - } - builder.endObject(); - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/PrefixFilterParser.java b/src/main/java/org/elasticsearch/index/query/PrefixFilterParser.java deleted file mode 100644 index d1f291e4606..00000000000 --- a/src/main/java/org/elasticsearch/index/query/PrefixFilterParser.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.apache.lucene.index.Term; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.PrefixQuery; -import org.apache.lucene.search.QueryWrapperFilter; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.lucene.BytesRefs; -import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.mapper.MapperService; - -import java.io.IOException; - -/** - * - */ -public class PrefixFilterParser implements FilterParser { - - public static final String NAME = "prefix"; - - @Inject - public PrefixFilterParser() { - } - - @Override - public String[] names() { - return new String[]{NAME}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - String fieldName = null; - Object value = null; - - String filterName = null; - String currentFieldName = null; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (token.isValue()) { - if ("_name".equals(currentFieldName)) { - filterName = parser.text(); - } else { - fieldName = currentFieldName; - value = parser.objectBytes(); - } - } - } - - if (value == null) { - throw new QueryParsingException(parseContext, "No value specified for prefix filter"); - } - - Filter filter = null; - - MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); - if (smartNameFieldMappers != null && smartNameFieldMappers.hasMapper()) { - filter = smartNameFieldMappers.mapper().prefixFilter(value, parseContext); - } - if (filter == null) { - filter = new QueryWrapperFilter(new PrefixQuery(new Term(fieldName, BytesRefs.toBytesRef(value)))); - } - - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); - } - return filter; - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/PrefixQueryParser.java b/src/main/java/org/elasticsearch/index/query/PrefixQueryParser.java index dc59007c461..893ec14dad3 100644 --- a/src/main/java/org/elasticsearch/index/query/PrefixQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/PrefixQueryParser.java @@ -51,42 +51,46 @@ public class PrefixQueryParser implements QueryParser { public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); - XContentParser.Token token = parser.nextToken(); - if (token != XContentParser.Token.FIELD_NAME) { - throw new QueryParsingException(parseContext, "[prefix] query malformed, no field"); - } String fieldName = parser.currentName(); String rewriteMethod = null; String queryName = null; Object value = null; float boost = 1.0f; - token = parser.nextToken(); - if (token == XContentParser.Token.START_OBJECT) { - String currentFieldName = null; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (token.isValue()) { - if ("prefix".equals(currentFieldName)) { - value = parser.objectBytes(); - } else if ("value".equals(currentFieldName)) { - value = parser.text(); - } else if ("boost".equals(currentFieldName)) { - boost = parser.floatValue(); - } else if ("rewrite".equals(currentFieldName)) { - rewriteMethod = parser.textOrNull(); - } else if ("_name".equals(currentFieldName)) { - queryName = parser.text(); + String currentFieldName = null; + XContentParser.Token token; + while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { + if (token == XContentParser.Token.FIELD_NAME) { + currentFieldName = parser.currentName(); + } else if (parseContext.isDeprecatedSetting(currentFieldName)) { + // skip + } else if (token == XContentParser.Token.START_OBJECT) { + fieldName = currentFieldName; + while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { + if (token == XContentParser.Token.FIELD_NAME) { + currentFieldName = parser.currentName(); + } else { + if ("_name".equals(currentFieldName)) { + queryName = parser.text(); + } else if ("value".equals(currentFieldName) || "prefix".equals(currentFieldName)) { + value = parser.objectBytes(); + } else if ("boost".equals(currentFieldName)) { + boost = parser.floatValue(); + } else if ("rewrite".equals(currentFieldName)) { + rewriteMethod = parser.textOrNull(); + } else { + throw new QueryParsingException(parseContext, "[regexp] query does not support [" + currentFieldName + "]"); + } } + } + } else { + if ("_name".equals(currentFieldName)) { + queryName = parser.text(); } else { - throw new QueryParsingException(parseContext, "[prefix] query does not support [" + currentFieldName + "]"); + fieldName = currentFieldName; + value = parser.objectBytes(); } } - parser.nextToken(); - } else { - value = parser.text(); - parser.nextToken(); } if (value == null) { diff --git a/src/main/java/org/elasticsearch/index/query/QueryBuilders.java b/src/main/java/org/elasticsearch/index/query/QueryBuilders.java index 12f5607cfc9..617841fe91d 100644 --- a/src/main/java/org/elasticsearch/index/query/QueryBuilders.java +++ b/src/main/java/org/elasticsearch/index/query/QueryBuilders.java @@ -19,7 +19,11 @@ package org.elasticsearch.index.query; +import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.common.Nullable; +import org.elasticsearch.common.bytes.BytesReference; +import org.elasticsearch.common.geo.GeoPoint; +import org.elasticsearch.common.geo.ShapeRelation; import org.elasticsearch.common.geo.builders.ShapeBuilder; import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder; import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder; @@ -352,20 +356,10 @@ public abstract class QueryBuilders { * @param queryBuilder The query to apply the filter to * @param filterBuilder The filter to apply on the query */ - public static FilteredQueryBuilder filteredQuery(@Nullable QueryBuilder queryBuilder, @Nullable FilterBuilder filterBuilder) { + public static FilteredQueryBuilder filteredQuery(@Nullable QueryBuilder queryBuilder, @Nullable QueryBuilder filterBuilder) { return new FilteredQueryBuilder(queryBuilder, filterBuilder); } - /** - * A query that wraps a filter and simply returns a constant score equal to the - * query boost for every document in the filter. - * - * @param filterBuilder The filter to wrap in a constant score query - */ - public static ConstantScoreQueryBuilder constantScoreQuery(FilterBuilder filterBuilder) { - return new ConstantScoreQueryBuilder(filterBuilder); - } - /** * A query that wraps another query and simply returns a constant score equal to the * query boost for every document in the query. @@ -411,45 +405,6 @@ public abstract class QueryBuilders { return (new FunctionScoreQueryBuilder(queryBuilder)).add(function); } - /** - * A query that allows to define a custom scoring function. - * - * @param filterBuilder The query to custom score - * @param function The function builder used to custom score - */ - public static FunctionScoreQueryBuilder functionScoreQuery(FilterBuilder filterBuilder, ScoreFunctionBuilder function) { - return (new FunctionScoreQueryBuilder(filterBuilder)).add(function); - } - - /** - * A query that allows to define a custom scoring function. - * - * @param filterBuilder The filterBuilder to custom score - */ - public static FunctionScoreQueryBuilder functionScoreQuery(FilterBuilder filterBuilder) { - return new FunctionScoreQueryBuilder(filterBuilder); - } - - /** - * A query that allows to define a custom scoring function. - * - * @param queryBuilder The query to custom score - * @param filterBuilder The filterBuilder to custom score - */ - public static FunctionScoreQueryBuilder functionScoreQuery(QueryBuilder queryBuilder, FilterBuilder filterBuilder) { - return new FunctionScoreQueryBuilder(queryBuilder, filterBuilder); - } - - /** - * A query that allows to define a custom scoring function. - * - * @param queryBuilder The query to custom score - * @param filterBuilder The filterBuilder to custom score - */ - public static FunctionScoreQueryBuilder functionScoreQuery(QueryBuilder queryBuilder, FilterBuilder filterBuilder, ScoreFunctionBuilder function) { - return (new FunctionScoreQueryBuilder(queryBuilder, filterBuilder)).add(function); - } - /** * A more like this query that finds documents that are "like" the provided {@link MoreLikeThisQueryBuilder#likeText(String)} * which is checked against the fields the query is constructed with. @@ -506,10 +461,6 @@ public abstract class QueryBuilders { return new NestedQueryBuilder(path, query); } - public static NestedQueryBuilder nestedQuery(String path, FilterBuilder filter) { - return new NestedQueryBuilder(path, filter); - } - /** * A filer for a field based on several terms matching on any of them. * @@ -613,10 +564,6 @@ public abstract class QueryBuilders { return new GeoShapeQueryBuilder(name, shape); } - public static GeoShapeQueryBuilder geoShapeQuery(String name, String indexedShapeId, String indexedShapeType) { - return new GeoShapeQueryBuilder(name, indexedShapeId, indexedShapeType); - } - /** * Facilitates creating template query requests using an inline script */ @@ -631,6 +578,241 @@ public abstract class QueryBuilders { return new TemplateQueryBuilder(template, templateType, vars); } + /** + * A filter based on doc/mapping type. + */ + public static TypeQueryBuilder typeQuery(String type) { + return new TypeQueryBuilder(type); + } + + /** + * A terms lookup filter for the provided field name. A lookup terms filter can + * extract the terms to filter by from another doc in an index. + */ + public static TermsLookupQueryBuilder termsLookupQuery(String name) { + return new TermsLookupQueryBuilder(name); + } + + /** + * A builder for filter based on a script. + * + * @param script The script to filter by. + */ + public static ScriptQueryBuilder scriptQuery(String script) { + return new ScriptQueryBuilder(script); + } + + /** + * A filter to filter based on a specific distance from a specific geo location / point. + * + * @param name The location field name. + */ + public static GeoDistanceQueryBuilder geoDistanceQuery(String name) { + return new GeoDistanceQueryBuilder(name); + } + + /** + * A filter to filter based on a specific range from a specific geo location / point. + * + * @param name The location field name. + */ + public static GeoDistanceRangeQueryBuilder geoDistanceRangeQuery(String name) { + return new GeoDistanceRangeQueryBuilder(name); + } + + /** + * A filter to filter based on a bounding box defined by top left and bottom right locations / points + * + * @param name The location field name. + */ + public static GeoBoundingBoxQueryBuilder geoBoundingBoxQuery(String name) { + return new GeoBoundingBoxQueryBuilder(name); + } + + /** + * A filter based on a bounding box defined by geohash. The field this filter is applied to + * must have {"type":"geo_point", "geohash":true} + * to work. + * + * @param name The geo point field name. + */ + public static GeohashCellQuery.Builder geoHashCellQuery(String name) { + return new GeohashCellQuery.Builder(name); + } + + /** + * A filter based on a bounding box defined by geohash. The field this filter is applied to + * must have {"type":"geo_point", "geohash":true} + * to work. + * + * @param name The geo point field name. + * @param geohash The Geohash to filter + */ + public static GeohashCellQuery.Builder geoHashCellQuery(String name, String geohash) { + return new GeohashCellQuery.Builder(name, geohash); + } + + /** + * A filter based on a bounding box defined by geohash. The field this filter is applied to + * must have {"type":"geo_point", "geohash":true} + * to work. + * + * @param name The geo point field name. + * @param point a geo point within the geohash bucket + */ + public static GeohashCellQuery.Builder geoHashCellQuery(String name, GeoPoint point) { + return new GeohashCellQuery.Builder(name, point); + } + + /** + * A filter based on a bounding box defined by geohash. The field this filter is applied to + * must have {"type":"geo_point", "geohash":true} + * to work. + * + * @param name The geo point field name + * @param geohash The Geohash to filter + * @param neighbors should the neighbor cell also be filtered + */ + public static GeohashCellQuery.Builder geoHashCellQuery(String name, String geohash, boolean neighbors) { + return new GeohashCellQuery.Builder(name, geohash, neighbors); + } + + /** + * A filter to filter based on a polygon defined by a set of locations / points. + * + * @param name The location field name. + */ + public static GeoPolygonQueryBuilder geoPolygonQuery(String name) { + return new GeoPolygonQueryBuilder(name); + } + + /** + * A filter based on the relationship of a shape and indexed shapes + * + * @param name The shape field name + * @param shape Shape to use in the filter + * @param relation relation of the shapes + */ + public static GeoShapeQueryBuilder geoShapeQuery(String name, ShapeBuilder shape, ShapeRelation relation) { + return new GeoShapeQueryBuilder(name, shape, relation); + } + + public static GeoShapeQueryBuilder geoShapeQuery(String name, String indexedShapeId, String indexedShapeType, ShapeRelation relation) { + return new GeoShapeQueryBuilder(name, indexedShapeId, indexedShapeType, relation); + } + + public static GeoShapeQueryBuilder geoShapeQuery(String name, String indexedShapeId, String indexedShapeType) { + return geoShapeQuery(name, indexedShapeId, indexedShapeType, null); + } + + /** + * A filter to filter indexed shapes intersecting with shapes + * + * @param name The shape field name + * @param shape Shape to use in the filter + */ + public static GeoShapeQueryBuilder geoIntersectionQuery(String name, ShapeBuilder shape) { + return geoShapeQuery(name, shape, ShapeRelation.INTERSECTS); + } + + public static GeoShapeQueryBuilder geoIntersectionQuery(String name, String indexedShapeId, String indexedShapeType) { + return geoShapeQuery(name, indexedShapeId, indexedShapeType, ShapeRelation.INTERSECTS); + } + + /** + * A filter to filter indexed shapes that are contained by a shape + * + * @param name The shape field name + * @param shape Shape to use in the filter + */ + public static GeoShapeQueryBuilder geoWithinQuery(String name, ShapeBuilder shape) { + return geoShapeQuery(name, shape, ShapeRelation.WITHIN); + } + + public static GeoShapeQueryBuilder geoWithinQuery(String name, String indexedShapeId, String indexedShapeType) { + return geoShapeQuery(name, indexedShapeId, indexedShapeType, ShapeRelation.WITHIN); + } + + /** + * A filter to filter indexed shapes that are not intersection with the query shape + * + * @param name The shape field name + * @param shape Shape to use in the filter + */ + public static GeoShapeQueryBuilder geoDisjointQuery(String name, ShapeBuilder shape) { + return geoShapeQuery(name, shape, ShapeRelation.DISJOINT); + } + + public static GeoShapeQueryBuilder geoDisjointQuery(String name, String indexedShapeId, String indexedShapeType) { + return geoShapeQuery(name, indexedShapeId, indexedShapeType, ShapeRelation.DISJOINT); + } + + /** + * A filter to filter only documents where a field exists in them. + * + * @param name The name of the field + */ + public static ExistsQueryBuilder existsQuery(String name) { + return new ExistsQueryBuilder(name); + } + + /** + * A filter to filter only documents where a field does not exists in them. + * + * @param name The name of the field + */ + public static MissingQueryBuilder missingQuery(String name) { + return new MissingQueryBuilder(name); + } + + public static NotQueryBuilder notQuery(QueryBuilder filter) { + return new NotQueryBuilder(filter); + } + + /** + * Constructs a bytes filter to generate a filter from a {@link BytesReference} source + * + * @param source The filter source + */ + public static BytesQueryBuilder bytesQuery(BytesReference source) { + return new BytesQueryBuilder(source); + } + + /** + * Create a new {@link OrQueryBuilder} composed of the given filters. + * @deprecated Use {@link #boolQuery()} instead + */ + @Deprecated + public static OrQueryBuilder orQuery(QueryBuilder... filters) { + return new OrQueryBuilder(filters); + } + + /** + * Create a new {@link AndQueryBuilder} composed of the given filters. + * @deprecated Use {@link #boolQuery()} instead + */ + @Deprecated + public static AndQueryBuilder andQuery(QueryBuilder... filters) { + return new AndQueryBuilder(filters); + } + + /** + * @deprecated Use {@link SearchRequestBuilder#setTerminateAfter(int)} instead + */ + @Deprecated + public static LimitQueryBuilder limitQuery(int limit) { + return new LimitQueryBuilder(limit); + } + + /** + * @deprecated Useless now that queries and filters are merged: pass the + * query as a filter directly. + */ + @Deprecated + public static QueryFilterBuilder queryFilter(QueryBuilder query) { + return new QueryFilterBuilder(query); + } + private QueryBuilders() { } diff --git a/src/main/java/org/elasticsearch/index/query/QueryFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/QueryFilterBuilder.java index c4af2419b5c..9c602b06f86 100644 --- a/src/main/java/org/elasticsearch/index/query/QueryFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/QueryFilterBuilder.java @@ -25,14 +25,15 @@ import java.io.IOException; /** * A filter that simply wraps a query. - * - * + * @deprecated Useless now that queries and filters are merged: pass the + * query as a filter directly. */ -public class QueryFilterBuilder extends BaseFilterBuilder { +@Deprecated +public class QueryFilterBuilder extends BaseQueryBuilder { private final QueryBuilder queryBuilder; - private String filterName; + private String queryName; /** * A filter that simply wraps a query. @@ -44,24 +45,24 @@ public class QueryFilterBuilder extends BaseFilterBuilder { } /** - * Sets the filter name for the filter that can be used when searching for matched_filters per hit. + * Sets the query name for the filter that can be used when searching for matched_filters per hit. */ - public QueryFilterBuilder filterName(String filterName) { - this.filterName = filterName; + public QueryFilterBuilder queryName(String queryName) { + this.queryName = queryName; return this; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { - if (filterName == null) { + if (queryName == null) { builder.field(QueryFilterParser.NAME); queryBuilder.toXContent(builder, params); } else { builder.startObject(FQueryFilterParser.NAME); builder.field("query"); queryBuilder.toXContent(builder, params); - if (filterName != null) { - builder.field("_name", filterName); + if (queryName != null) { + builder.field("_name", queryName); } builder.endObject(); } diff --git a/src/main/java/org/elasticsearch/index/query/QueryFilterParser.java b/src/main/java/org/elasticsearch/index/query/QueryFilterParser.java index bdc09dbee78..fdb9cb3c0d8 100644 --- a/src/main/java/org/elasticsearch/index/query/QueryFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/QueryFilterParser.java @@ -19,17 +19,14 @@ package org.elasticsearch.index.query; -import org.apache.lucene.search.Filter; +import org.apache.lucene.search.ConstantScoreQuery; import org.apache.lucene.search.Query; -import org.apache.lucene.search.QueryWrapperFilter; import org.elasticsearch.common.inject.Inject; import java.io.IOException; -/** - * - */ -public class QueryFilterParser implements FilterParser { +@Deprecated +public class QueryFilterParser implements QueryParser { public static final String NAME = "query"; @@ -43,11 +40,7 @@ public class QueryFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - Query query = parseContext.parseInnerQuery(); - if (query == null) { - return null; - } - return new QueryWrapperFilter(query); + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + return new ConstantScoreQuery(parseContext.parseInnerQuery()); } } \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/QueryParseContext.java b/src/main/java/org/elasticsearch/index/query/QueryParseContext.java index aaf247e90cc..6baf0b631bc 100644 --- a/src/main/java/org/elasticsearch/index/query/QueryParseContext.java +++ b/src/main/java/org/elasticsearch/index/query/QueryParseContext.java @@ -26,7 +26,6 @@ import org.apache.lucene.queryparser.classic.MapperQueryParser; import org.apache.lucene.queryparser.classic.QueryParserSettings; import org.apache.lucene.search.Filter; import org.apache.lucene.search.Query; -import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.join.BitDocIdSetFilter; import org.apache.lucene.search.similarities.Similarity; import org.elasticsearch.Version; @@ -93,7 +92,7 @@ public class QueryParseContext { private final IndexQueryParserService indexQueryParser; - private final Map namedFilters = Maps.newHashMap(); + private final Map namedQueries = Maps.newHashMap(); private final MapperQueryParser queryParser = new MapperQueryParser(this); @@ -107,6 +106,8 @@ public class QueryParseContext { private NestedScope nestedScope; + private boolean isFilter; + public QueryParseContext(Index index, IndexQueryParserService indexQueryParser) { this.index = index; this.indexQueryParser = indexQueryParser; @@ -125,8 +126,9 @@ public class QueryParseContext { this.parseFlags = ParseField.EMPTY_FLAGS; this.lookup = null; this.parser = jp; - this.namedFilters.clear(); + this.namedQueries.clear(); this.nestedScope = new NestedScope(); + this.isFilter = false; } public Index index() { @@ -187,20 +189,23 @@ public class QueryParseContext { return indexQueryParser.fieldDataService.getForField(mapper); } - public void addNamedFilter(String name, Filter filter) { - namedFilters.put(name, filter); - } - public void addNamedQuery(String name, Query query) { - namedFilters.put(name, new QueryWrapperFilter(query)); + namedQueries.put(name, query); } - public ImmutableMap copyNamedFilters() { - return ImmutableMap.copyOf(namedFilters); + public ImmutableMap copyNamedFilters() { + return ImmutableMap.copyOf(namedQueries); } public void combineNamedFilters(QueryParseContext context) { - namedFilters.putAll(context.namedFilters); + namedQueries.putAll(context.namedQueries); + } + + /** + * Return whether we are currently parsing a filter or a query. + */ + public boolean isFilter() { + return isFilter; } public void addInnerHits(String name, InnerHitsContext.BaseInnerHits context) { @@ -216,7 +221,7 @@ public class QueryParseContext { } @Nullable - public Query parseInnerQuery() throws IOException, QueryParsingException { + public Query parseInnerQuery() throws QueryParsingException, IOException { // move to START object XContentParser.Token token; if (parser.currentToken() != XContentParser.Token.START_OBJECT) { @@ -226,6 +231,11 @@ public class QueryParseContext { } } token = parser.nextToken(); + if (token == XContentParser.Token.END_OBJECT) { + // empty query + parser.nextToken(); + return null; + } if (token != XContentParser.Token.FIELD_NAME) { throw new QueryParsingException(this, "[_na] query malformed, no field after start_object"); } @@ -249,48 +259,28 @@ public class QueryParseContext { } @Nullable - public Filter parseInnerFilter() throws IOException, QueryParsingException { - // move to START object - XContentParser.Token token; - if (parser.currentToken() != XContentParser.Token.START_OBJECT) { - token = parser.nextToken(); - if (token != XContentParser.Token.START_OBJECT) { - throw new QueryParsingException(this, "[_na] filter malformed, must start with start_object"); - } + public Query parseInnerFilter() throws QueryParsingException, IOException { + final boolean originalIsFilter = isFilter; + try { + isFilter = true; + return parseInnerQuery(); + } finally { + isFilter = originalIsFilter; } - token = parser.nextToken(); - if (token != XContentParser.Token.FIELD_NAME) { - // empty filter - if (token == XContentParser.Token.END_OBJECT || token == XContentParser.Token.VALUE_NULL) { - return null; - } - throw new QueryParsingException(this, "[_na] filter malformed, no field after start_object"); - } - String filterName = parser.currentName(); - // move to the next START_OBJECT or START_ARRAY - token = parser.nextToken(); - if (token != XContentParser.Token.START_OBJECT && token != XContentParser.Token.START_ARRAY) { - throw new QueryParsingException(this, "[_na] filter malformed, no field after start_object"); - } - - FilterParser filterParser = indexQueryParser.filterParser(filterName); - if (filterParser == null) { - throw new QueryParsingException(this, "No filter registered for [" + filterName + "]"); - } - Filter result = filterParser.parse(this); - if (parser.currentToken() == XContentParser.Token.END_OBJECT || parser.currentToken() == XContentParser.Token.END_ARRAY) { - // if we are at END_OBJECT, move to the next one... - parser.nextToken(); - } - return result; } - public Filter parseInnerFilter(String filterName) throws IOException, QueryParsingException { - FilterParser filterParser = indexQueryParser.filterParser(filterName); - if (filterParser == null) { - throw new QueryParsingException(this, "No filter registered for [" + filterName + "]"); + public Query parseInnerFilter(String queryName) throws IOException, QueryParsingException { + final boolean originalIsFilter = isFilter; + try { + isFilter = true; + QueryParser queryParser = indexQueryParser.queryParser(queryName); + if (queryParser == null) { + throw new QueryParsingException(this, "No query registered for [" + queryName + "]"); + } + return queryParser.parse(this); + } finally { + isFilter = originalIsFilter; } - return filterParser.parse(this); } public FieldMapper fieldMapper(String name) { diff --git a/src/main/java/org/elasticsearch/index/query/RangeFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/RangeFilterBuilder.java deleted file mode 100644 index 42753179b07..00000000000 --- a/src/main/java/org/elasticsearch/index/query/RangeFilterBuilder.java +++ /dev/null @@ -1,390 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.common.xcontent.XContentBuilder; - -import java.io.IOException; - -/** - * A filter that restricts search results to values that are within the given range. - * - * - */ -public class RangeFilterBuilder extends BaseFilterBuilder { - - private final String name; - - private Object from; - - private Object to; - private String timeZone; - - private boolean includeLower = true; - - private boolean includeUpper = true; - - private String filterName; - - private String execution; - - /** - * A filter that restricts search results to values that are within the given range. - * - * @param name The field name - */ - public RangeFilterBuilder(String name) { - this.name = name; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder from(Object from) { - this.from = from; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder from(int from) { - this.from = from; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder from(long from) { - this.from = from; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder from(float from) { - this.from = from; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder from(double from) { - this.from = from; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder gt(Object from) { - this.from = from; - this.includeLower = false; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder gt(int from) { - this.from = from; - this.includeLower = false; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder gt(long from) { - this.from = from; - this.includeLower = false; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder gt(float from) { - this.from = from; - this.includeLower = false; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder gt(double from) { - this.from = from; - this.includeLower = false; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder gte(Object from) { - this.from = from; - this.includeLower = true; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder gte(int from) { - this.from = from; - this.includeLower = true; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder gte(long from) { - this.from = from; - this.includeLower = true; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder gte(float from) { - this.from = from; - this.includeLower = true; - return this; - } - - /** - * The from part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder gte(double from) { - this.from = from; - this.includeLower = true; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder to(Object to) { - this.to = to; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder to(int to) { - this.to = to; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder to(long to) { - this.to = to; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder to(float to) { - this.to = to; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder to(double to) { - this.to = to; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder lt(Object to) { - this.to = to; - this.includeUpper = false; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder lt(int to) { - this.to = to; - this.includeUpper = false; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder lt(long to) { - this.to = to; - this.includeUpper = false; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder lt(float to) { - this.to = to; - this.includeUpper = false; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder lt(double to) { - this.to = to; - this.includeUpper = false; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder lte(int to) { - this.to = to; - this.includeUpper = true; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder lte(long to) { - this.to = to; - this.includeUpper = true; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder lte(float to) { - this.to = to; - this.includeUpper = true; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder lte(double to) { - this.to = to; - this.includeUpper = true; - return this; - } - - /** - * The to part of the filter query. Null indicates unbounded. - */ - public RangeFilterBuilder lte(Object to) { - this.to = to; - this.includeUpper = true; - return this; - } - - /** - * Should the lower bound be included or not. Defaults to true. - */ - public RangeFilterBuilder includeLower(boolean includeLower) { - this.includeLower = includeLower; - return this; - } - - /** - * Should the upper bound be included or not. Defaults to true. - */ - public RangeFilterBuilder includeUpper(boolean includeUpper) { - this.includeUpper = includeUpper; - return this; - } - - /** - * Sets the filter name for the filter that can be used when searching for matched_filters per hit. - */ - public RangeFilterBuilder filterName(String filterName) { - this.filterName = filterName; - return this; - } - - /** - * Sets the execution mode that controls how the range filter is executed. Valid values are: "index" and "fielddata". - *
    - *
  1. The index execution uses the field's inverted in order to determine of documents fall with in - * the range filter's from and to range. - *
  2. The fielddata execution uses field data in order to determine of documents fall with in the - * range filter's from and to range. Since field data is an in memory data structure, you need to have - * sufficient memory on your nodes in order to use this execution mode. - *
- * - * In general for small ranges the index execution is faster and for longer ranges the - * fielddata execution is faster. - */ - public RangeFilterBuilder setExecution(String execution) { - this.execution = execution; - return this; - } - - /** - * In case of date field, we can adjust the from/to fields using a timezone - */ - public RangeFilterBuilder timeZone(String timeZone) { - this.timeZone = timeZone; - return this; - } - - @Override - protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(RangeFilterParser.NAME); - - builder.startObject(name); - builder.field("from", from); - builder.field("to", to); - if (timeZone != null) { - builder.field("time_zone", timeZone); - } - builder.field("include_lower", includeLower); - builder.field("include_upper", includeUpper); - builder.endObject(); - - if (filterName != null) { - builder.field("_name", filterName); - } - if (execution != null) { - builder.field("execution", execution); - } - - builder.endObject(); - } -} diff --git a/src/main/java/org/elasticsearch/index/query/RangeFilterParser.java b/src/main/java/org/elasticsearch/index/query/RangeFilterParser.java deleted file mode 100644 index 83650aecd5d..00000000000 --- a/src/main/java/org/elasticsearch/index/query/RangeFilterParser.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.QueryWrapperFilter; -import org.apache.lucene.search.TermRangeQuery; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.joda.DateMathParser; -import org.elasticsearch.common.joda.Joda; -import org.elasticsearch.common.lucene.BytesRefs; -import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.mapper.FieldMapper; -import org.elasticsearch.index.mapper.MapperService; -import org.elasticsearch.index.mapper.core.DateFieldMapper; -import org.elasticsearch.index.mapper.core.NumberFieldMapper; -import org.joda.time.DateTimeZone; - -import java.io.IOException; - -/** - * - */ -public class RangeFilterParser implements FilterParser { - - public static final String NAME = "range"; - - @Inject - public RangeFilterParser() { - } - - @Override - public String[] names() { - return new String[]{NAME}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - String fieldName = null; - Object from = null; - Object to = null; - boolean includeLower = true; - boolean includeUpper = true; - DateTimeZone timeZone = null; - DateMathParser forcedDateParser = null; - String execution = "index"; - - String filterName = null; - String currentFieldName = null; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (parseContext.isDeprecatedSetting(currentFieldName)) { - // skip - } else if (token == XContentParser.Token.START_OBJECT) { - fieldName = currentFieldName; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else { - if ("from".equals(currentFieldName)) { - from = parser.objectBytes(); - } else if ("to".equals(currentFieldName)) { - to = parser.objectBytes(); - } else if ("include_lower".equals(currentFieldName) || "includeLower".equals(currentFieldName)) { - includeLower = parser.booleanValue(); - } else if ("include_upper".equals(currentFieldName) || "includeUpper".equals(currentFieldName)) { - includeUpper = parser.booleanValue(); - } else if ("gt".equals(currentFieldName)) { - from = parser.objectBytes(); - includeLower = false; - } else if ("gte".equals(currentFieldName) || "ge".equals(currentFieldName)) { - from = parser.objectBytes(); - includeLower = true; - } else if ("lt".equals(currentFieldName)) { - to = parser.objectBytes(); - includeUpper = false; - } else if ("lte".equals(currentFieldName) || "le".equals(currentFieldName)) { - to = parser.objectBytes(); - includeUpper = true; - } else if ("time_zone".equals(currentFieldName) || "timeZone".equals(currentFieldName)) { - timeZone = DateTimeZone.forID(parser.text()); - } else if ("format".equals(currentFieldName)) { - forcedDateParser = new DateMathParser(Joda.forPattern(parser.text()), DateFieldMapper.Defaults.TIME_UNIT); - } else { - throw new QueryParsingException(parseContext, "[range] filter does not support [" + currentFieldName + "]"); - } - } - } - } else if (token.isValue()) { - if ("_name".equals(currentFieldName)) { - filterName = parser.text(); - } else if ("execution".equals(currentFieldName)) { - execution = parser.text(); - } else { - throw new QueryParsingException(parseContext, "[range] filter does not support [" + currentFieldName + "]"); - } - } - } - - if (fieldName == null) { - throw new QueryParsingException(parseContext, "[range] filter no field specified for range filter"); - } - - Filter filter = null; - MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); - if (smartNameFieldMappers != null) { - if (smartNameFieldMappers.hasMapper()) { - if (execution.equals("index")) { - FieldMapper mapper = smartNameFieldMappers.mapper(); - if (mapper instanceof DateFieldMapper) { - if ((from instanceof Number || to instanceof Number) && timeZone != null) { - throw new QueryParsingException(parseContext, - "[range] time_zone when using ms since epoch format as it's UTC based can not be applied to [" - + fieldName + "]"); - } - filter = ((DateFieldMapper) mapper).rangeFilter(from, to, includeLower, includeUpper, timeZone, forcedDateParser, parseContext); - } else { - if (timeZone != null) { - throw new QueryParsingException(parseContext, "[range] time_zone can not be applied to non date field [" - + fieldName + "]"); - } - filter = mapper.rangeFilter(from, to, includeLower, includeUpper, parseContext); - } - } else if ("fielddata".equals(execution)) { - FieldMapper mapper = smartNameFieldMappers.mapper(); - if (!(mapper instanceof NumberFieldMapper)) { - throw new QueryParsingException(parseContext, "[range] filter field [" + fieldName + "] is not a numeric type"); - } - if (mapper instanceof DateFieldMapper) { - if ((from instanceof Number || to instanceof Number) && timeZone != null) { - throw new QueryParsingException(parseContext, - "[range] time_zone when using ms since epoch format as it's UTC based can not be applied to [" - + fieldName + "]"); - } - filter = ((DateFieldMapper) mapper).rangeFilter(parseContext, from, to, includeLower, includeUpper, timeZone, forcedDateParser, parseContext); - } else { - if (timeZone != null) { - throw new QueryParsingException(parseContext, "[range] time_zone can not be applied to non date field [" - + fieldName + "]"); - } - filter = ((NumberFieldMapper) mapper).rangeFilter(parseContext, from, to, includeLower, includeUpper, parseContext); - } - } else { - throw new QueryParsingException(parseContext, "[range] filter doesn't support [" + execution + "] execution"); - } - } - } - - if (filter == null) { - filter = new QueryWrapperFilter(new TermRangeQuery(fieldName, BytesRefs.toBytesRef(from), BytesRefs.toBytesRef(to), includeLower, includeUpper)); - } - - - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); - } - return filter; - } -} diff --git a/src/main/java/org/elasticsearch/index/query/RangeQueryBuilder.java b/src/main/java/org/elasticsearch/index/query/RangeQueryBuilder.java index 7ed99d6e571..ac2c210367f 100644 --- a/src/main/java/org/elasticsearch/index/query/RangeQueryBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/RangeQueryBuilder.java @@ -422,10 +422,10 @@ public class RangeQueryBuilder extends BaseQueryBuilder implements MultiTermQuer if (boost != -1) { builder.field("boost", boost); } + builder.endObject(); if (queryName != null) { builder.field("_name", queryName); } builder.endObject(); - builder.endObject(); } } diff --git a/src/main/java/org/elasticsearch/index/query/RangeQueryParser.java b/src/main/java/org/elasticsearch/index/query/RangeQueryParser.java index 354da1df704..4c51b2eb4d2 100644 --- a/src/main/java/org/elasticsearch/index/query/RangeQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/RangeQueryParser.java @@ -21,6 +21,7 @@ package org.elasticsearch.index.query; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermRangeQuery; +import org.elasticsearch.common.ParseField; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.joda.DateMathParser; import org.elasticsearch.common.joda.Joda; @@ -39,6 +40,7 @@ import java.io.IOException; public class RangeQueryParser implements QueryParser { public static final String NAME = "range"; + private static final ParseField FIELDDATA_FIELD = new ParseField("fielddata").withAllDeprecated("[no replacement]"); @Inject public RangeQueryParser() { @@ -53,16 +55,7 @@ public class RangeQueryParser implements QueryParser { public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); - XContentParser.Token token = parser.nextToken(); - if (token != XContentParser.Token.FIELD_NAME) { - throw new QueryParsingException(parseContext, "[range] query malformed, no field to indicate field name"); - } - String fieldName = parser.currentName(); - token = parser.nextToken(); - if (token != XContentParser.Token.START_OBJECT) { - throw new QueryParsingException(parseContext, "[range] query malformed, after field missing start object"); - } - + String fieldName = null; Object from = null; Object to = null; boolean includeLower = true; @@ -73,50 +66,60 @@ public class RangeQueryParser implements QueryParser { String queryName = null; String currentFieldName = null; + XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); - } else { - if ("from".equals(currentFieldName)) { - from = parser.objectBytes(); - } else if ("to".equals(currentFieldName)) { - to = parser.objectBytes(); - } else if ("include_lower".equals(currentFieldName) || "includeLower".equals(currentFieldName)) { - includeLower = parser.booleanValue(); - } else if ("include_upper".equals(currentFieldName) || "includeUpper".equals(currentFieldName)) { - includeUpper = parser.booleanValue(); - } else if ("boost".equals(currentFieldName)) { - boost = parser.floatValue(); - } else if ("gt".equals(currentFieldName)) { - from = parser.objectBytes(); - includeLower = false; - } else if ("gte".equals(currentFieldName) || "ge".equals(currentFieldName)) { - from = parser.objectBytes(); - includeLower = true; - } else if ("lt".equals(currentFieldName)) { - to = parser.objectBytes(); - includeUpper = false; - } else if ("lte".equals(currentFieldName) || "le".equals(currentFieldName)) { - to = parser.objectBytes(); - includeUpper = true; - } else if ("time_zone".equals(currentFieldName) || "timeZone".equals(currentFieldName)) { - timeZone = DateTimeZone.forID(parser.text()); - } else if ("_name".equals(currentFieldName)) { + } else if (parseContext.isDeprecatedSetting(currentFieldName)) { + // skip + } else if (token == XContentParser.Token.START_OBJECT) { + fieldName = currentFieldName; + while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { + if (token == XContentParser.Token.FIELD_NAME) { + currentFieldName = parser.currentName(); + } else { + if ("from".equals(currentFieldName)) { + from = parser.objectBytes(); + } else if ("to".equals(currentFieldName)) { + to = parser.objectBytes(); + } else if ("include_lower".equals(currentFieldName) || "includeLower".equals(currentFieldName)) { + includeLower = parser.booleanValue(); + } else if ("include_upper".equals(currentFieldName) || "includeUpper".equals(currentFieldName)) { + includeUpper = parser.booleanValue(); + } else if ("boost".equals(currentFieldName)) { + boost = parser.floatValue(); + } else if ("gt".equals(currentFieldName)) { + from = parser.objectBytes(); + includeLower = false; + } else if ("gte".equals(currentFieldName) || "ge".equals(currentFieldName)) { + from = parser.objectBytes(); + includeLower = true; + } else if ("lt".equals(currentFieldName)) { + to = parser.objectBytes(); + includeUpper = false; + } else if ("lte".equals(currentFieldName) || "le".equals(currentFieldName)) { + to = parser.objectBytes(); + includeUpper = true; + } else if ("time_zone".equals(currentFieldName) || "timeZone".equals(currentFieldName)) { + timeZone = DateTimeZone.forID(parser.text()); + } else if ("format".equals(currentFieldName)) { + forcedDateParser = new DateMathParser(Joda.forPattern(parser.text()), DateFieldMapper.Defaults.TIME_UNIT); + } else { + throw new QueryParsingException(parseContext, "[range] query does not support [" + currentFieldName + "]"); + } + } + } + } else if (token.isValue()) { + if ("_name".equals(currentFieldName)) { queryName = parser.text(); - } else if ("format".equals(currentFieldName)) { - forcedDateParser = new DateMathParser(Joda.forPattern(parser.text()), DateFieldMapper.Defaults.TIME_UNIT); + } else if (FIELDDATA_FIELD.match(currentFieldName)) { + // ignore } else { throw new QueryParsingException(parseContext, "[range] query does not support [" + currentFieldName + "]"); } } } - // move to the next end object, to close the field name - token = parser.nextToken(); - if (token != XContentParser.Token.END_OBJECT) { - throw new QueryParsingException(parseContext, "[range] query malformed, does not end with an object"); - } - Query query = null; MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); if (smartNameFieldMappers != null) { diff --git a/src/main/java/org/elasticsearch/index/query/RegexpFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/RegexpFilterBuilder.java deleted file mode 100644 index f730c084be3..00000000000 --- a/src/main/java/org/elasticsearch/index/query/RegexpFilterBuilder.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.apache.lucene.util.automaton.Operations; -import org.elasticsearch.common.xcontent.XContentBuilder; - -import java.io.IOException; - -/** - * A filter that restricts search results to values that have a matching regular expression in a given - * field. - * - * - */ -public class RegexpFilterBuilder extends BaseFilterBuilder { - - private final String name; - private final String regexp; - private int flags = -1; - private int maxDeterminizedStates = Operations.DEFAULT_MAX_DETERMINIZED_STATES; - private boolean maxDetermizedStatesSet; - - private String filterName; - - /** - * A filter that restricts search results to values that have a matching prefix in a given - * field. - * - * @param name The field name - * @param regexp The regular expression - */ - public RegexpFilterBuilder(String name, String regexp) { - this.name = name; - this.regexp = regexp; - } - - /** - * Sets the filter name for the filter that can be used when searching for matched_filters per hit. - */ - public RegexpFilterBuilder filterName(String filterName) { - this.filterName = filterName; - return this; - } - - /** - * Sets the regexp flags (see {@link RegexpFlag}). - */ - public RegexpFilterBuilder flags(RegexpFlag... flags) { - int value = 0; - if (flags.length == 0) { - value = RegexpFlag.ALL.value; - } else { - for (RegexpFlag flag : flags) { - value |= flag.value; - } - } - this.flags = value; - return this; - } - - /** - * Sets the regexp maxDeterminizedStates. - */ - public RegexpFilterBuilder maxDeterminizedStates(int value) { - this.maxDeterminizedStates = value; - this.maxDetermizedStatesSet = true; - return this; - } - - @Override - public void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(RegexpFilterParser.NAME); - if (flags < 0) { - builder.field(name, regexp); - } else { - builder.startObject(name) - .field("value", regexp) - .field("flags_value", flags); - if (maxDetermizedStatesSet) { - builder.field("max_determinized_states", maxDeterminizedStates); - } - builder.endObject(); - } - - if (filterName != null) { - builder.field("_name", filterName); - } - builder.endObject(); - } -} diff --git a/src/main/java/org/elasticsearch/index/query/RegexpFilterParser.java b/src/main/java/org/elasticsearch/index/query/RegexpFilterParser.java deleted file mode 100644 index 9612812ffe9..00000000000 --- a/src/main/java/org/elasticsearch/index/query/RegexpFilterParser.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.apache.lucene.index.Term; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.QueryWrapperFilter; -import org.apache.lucene.search.RegexpQuery; -import org.apache.lucene.util.automaton.Operations; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.lucene.BytesRefs; -import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.mapper.MapperService; - -import java.io.IOException; - -/** - * - */ -public class RegexpFilterParser implements FilterParser { - - public static final String NAME = "regexp"; - - @Inject - public RegexpFilterParser() { - } - - @Override - public String[] names() { - return new String[]{NAME}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - String fieldName = null; - String secondaryFieldName = null; - Object value = null; - Object secondaryValue = null; - int flagsValue = -1; - - String filterName = null; - String currentFieldName = null; - int maxDeterminizedStates = Operations.DEFAULT_MAX_DETERMINIZED_STATES; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (parseContext.isDeprecatedSetting(currentFieldName)) { - // skip - } else if (token == XContentParser.Token.START_OBJECT) { - fieldName = currentFieldName; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else { - if ("value".equals(currentFieldName)) { - value = parser.objectBytes(); - } else if ("flags".equals(currentFieldName)) { - String flags = parser.textOrNull(); - flagsValue = RegexpFlag.resolveValue(flags); - } else if ("max_determinized_states".equals(currentFieldName)) { - maxDeterminizedStates = parser.intValue(); - } else if ("flags_value".equals(currentFieldName)) { - flagsValue = parser.intValue(); - } else { - throw new QueryParsingException(parseContext, "[regexp] filter does not support [" + currentFieldName + "]"); - } - } - } - } else { - if ("_name".equals(currentFieldName)) { - filterName = parser.text(); - } else { - secondaryFieldName = currentFieldName; - secondaryValue = parser.objectBytes(); - } - } - } - - if (fieldName == null) { - fieldName = secondaryFieldName; - value = secondaryValue; - } - - if (value == null) { - throw new QueryParsingException(parseContext, "No value specified for regexp filter"); - } - - Filter filter = null; - - MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); - if (smartNameFieldMappers != null && smartNameFieldMappers.hasMapper()) { - filter = smartNameFieldMappers.mapper().regexpFilter(value, flagsValue, maxDeterminizedStates, parseContext); - } - if (filter == null) { - filter = new QueryWrapperFilter(new RegexpQuery(new Term(fieldName, BytesRefs.toBytesRef(value)), flagsValue, maxDeterminizedStates)); - } - - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); - } - return filter; - } -} diff --git a/src/main/java/org/elasticsearch/index/query/RegexpFlag.java b/src/main/java/org/elasticsearch/index/query/RegexpFlag.java index d2a3eafea56..0af6b86db30 100644 --- a/src/main/java/org/elasticsearch/index/query/RegexpFlag.java +++ b/src/main/java/org/elasticsearch/index/query/RegexpFlag.java @@ -36,7 +36,7 @@ import org.elasticsearch.common.Strings; * * * @see RegexpQueryBuilder#flags(RegexpFlag...) - * @see RegexpFilterBuilder#flags(RegexpFlag...) + * @see RegexpQueryBuilder#flags(RegexpFlag...) */ public enum RegexpFlag { diff --git a/src/main/java/org/elasticsearch/index/query/RegexpQueryParser.java b/src/main/java/org/elasticsearch/index/query/RegexpQueryParser.java index a1ec2996332..6a0b9eb4249 100644 --- a/src/main/java/org/elasticsearch/index/query/RegexpQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/RegexpQueryParser.java @@ -53,10 +53,6 @@ public class RegexpQueryParser implements QueryParser { public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); - XContentParser.Token token = parser.nextToken(); - if (token != XContentParser.Token.FIELD_NAME) { - throw new QueryParsingException(parseContext, "[regexp] query malformed, no field"); - } String fieldName = parser.currentName(); String rewriteMethod = null; @@ -65,40 +61,45 @@ public class RegexpQueryParser implements QueryParser { int flagsValue = -1; int maxDeterminizedStates = Operations.DEFAULT_MAX_DETERMINIZED_STATES; String queryName = null; - token = parser.nextToken(); - if (token == XContentParser.Token.START_OBJECT) { - String currentFieldName = null; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (token.isValue()) { - if ("value".equals(currentFieldName)) { - value = parser.objectBytes(); - } else if ("boost".equals(currentFieldName)) { - boost = parser.floatValue(); - } else if ("rewrite".equals(currentFieldName)) { - rewriteMethod = parser.textOrNull(); - } else if ("flags".equals(currentFieldName)) { - String flags = parser.textOrNull(); - flagsValue = RegexpFlag.resolveValue(flags); - } else if ("flags_value".equals(currentFieldName)) { - flagsValue = parser.intValue(); - if (flagsValue < 0) { - flagsValue = RegExp.ALL; + String currentFieldName = null; + XContentParser.Token token; + while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { + if (token == XContentParser.Token.FIELD_NAME) { + currentFieldName = parser.currentName(); + } else if (parseContext.isDeprecatedSetting(currentFieldName)) { + // skip + } else if (token == XContentParser.Token.START_OBJECT) { + fieldName = currentFieldName; + while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { + if (token == XContentParser.Token.FIELD_NAME) { + currentFieldName = parser.currentName(); + } else { + if ("value".equals(currentFieldName)) { + value = parser.objectBytes(); + } else if ("boost".equals(currentFieldName)) { + boost = parser.floatValue(); + } else if ("rewrite".equals(currentFieldName)) { + rewriteMethod = parser.textOrNull(); + } else if ("flags".equals(currentFieldName)) { + String flags = parser.textOrNull(); + flagsValue = RegexpFlag.resolveValue(flags); + } else if ("max_determinized_states".equals(currentFieldName)) { + maxDeterminizedStates = parser.intValue(); + } else if ("flags_value".equals(currentFieldName)) { + flagsValue = parser.intValue(); + } else { + throw new QueryParsingException(parseContext, "[regexp] query does not support [" + currentFieldName + "]"); } - } else if ("maxDeterminizedStates".equals(currentFieldName)) { - maxDeterminizedStates = parser.intValue(); - } else if ("_name".equals(currentFieldName)) { - queryName = parser.text(); } + } + } else { + if ("_name".equals(currentFieldName)) { + queryName = parser.text(); } else { - throw new QueryParsingException(parseContext, "[regexp] query does not support [" + currentFieldName + "]"); + fieldName = currentFieldName; + value = parser.objectBytes(); } } - parser.nextToken(); - } else { - value = parser.objectBytes(); - parser.nextToken(); } if (value == null) { diff --git a/src/main/java/org/elasticsearch/index/query/ScriptFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/ScriptQueryBuilder.java similarity index 78% rename from src/main/java/org/elasticsearch/index/query/ScriptFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/ScriptQueryBuilder.java index 89f0fe7f033..00f6ddff62b 100644 --- a/src/main/java/org/elasticsearch/index/query/ScriptFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/ScriptQueryBuilder.java @@ -29,7 +29,7 @@ import static com.google.common.collect.Maps.newHashMap; /** * */ -public class ScriptFilterBuilder extends BaseFilterBuilder { +public class ScriptQueryBuilder extends BaseQueryBuilder { private final String script; @@ -37,13 +37,13 @@ public class ScriptFilterBuilder extends BaseFilterBuilder { private String lang; - private String filterName; + private String queryName; - public ScriptFilterBuilder(String script) { + public ScriptQueryBuilder(String script) { this.script = script; } - public ScriptFilterBuilder addParam(String name, Object value) { + public ScriptQueryBuilder addParam(String name, Object value) { if (params == null) { params = newHashMap(); } @@ -51,7 +51,7 @@ public class ScriptFilterBuilder extends BaseFilterBuilder { return this; } - public ScriptFilterBuilder params(Map params) { + public ScriptQueryBuilder params(Map params) { if (this.params == null) { this.params = params; } else { @@ -63,7 +63,7 @@ public class ScriptFilterBuilder extends BaseFilterBuilder { /** * Sets the script language. */ - public ScriptFilterBuilder lang(String lang) { + public ScriptQueryBuilder lang(String lang) { this.lang = lang; return this; } @@ -71,14 +71,14 @@ public class ScriptFilterBuilder extends BaseFilterBuilder { /** * Sets the filter name for the filter that can be used when searching for matched_filters per hit. */ - public ScriptFilterBuilder filterName(String filterName) { - this.filterName = filterName; + public ScriptQueryBuilder queryName(String queryName) { + this.queryName = queryName; return this; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(ScriptFilterParser.NAME); + builder.startObject(ScriptQueryParser.NAME); builder.field("script", script); if (this.params != null) { builder.field("params", this.params); @@ -86,8 +86,8 @@ public class ScriptFilterBuilder extends BaseFilterBuilder { if (this.lang != null) { builder.field("lang", lang); } - if (filterName != null) { - builder.field("_name", filterName); + if (queryName != null) { + builder.field("_name", queryName); } builder.endObject(); } diff --git a/src/main/java/org/elasticsearch/index/query/ScriptFilterParser.java b/src/main/java/org/elasticsearch/index/query/ScriptQueryParser.java similarity index 91% rename from src/main/java/org/elasticsearch/index/query/ScriptFilterParser.java rename to src/main/java/org/elasticsearch/index/query/ScriptQueryParser.java index 7e4b59a5748..598926cb1da 100644 --- a/src/main/java/org/elasticsearch/index/query/ScriptFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/ScriptQueryParser.java @@ -24,6 +24,7 @@ import org.apache.lucene.search.BitsFilteredDocIdSet; import org.apache.lucene.search.DocIdSet; import org.apache.lucene.search.DocValuesDocIdSet; import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.apache.lucene.util.Bits; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.inject.Inject; @@ -46,12 +47,12 @@ import static com.google.common.collect.Maps.newHashMap; /** * */ -public class ScriptFilterParser implements FilterParser { +public class ScriptQueryParser implements QueryParser { public static final String NAME = "script"; @Inject - public ScriptFilterParser() { + public ScriptQueryParser() { } @Override @@ -60,7 +61,7 @@ public class ScriptFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); ScriptParameterParser scriptParameterParser = new ScriptParameterParser(); @@ -71,7 +72,7 @@ public class ScriptFilterParser implements FilterParser { String scriptLang; Map params = null; - String filterName = null; + String queryName = null; String currentFieldName = null; ScriptService.ScriptType scriptType = null; @@ -84,13 +85,13 @@ public class ScriptFilterParser implements FilterParser { if ("params".equals(currentFieldName)) { params = parser.map(); } else { - throw new QueryParsingException(parseContext, "[script] filter does not support [" + currentFieldName + "]"); + throw new QueryParsingException(parseContext, "[script] query does not support [" + currentFieldName + "]"); } } else if (token.isValue()) { if ("_name".equals(currentFieldName)) { - filterName = parser.text(); + queryName = parser.text(); } else if (!scriptParameterParser.token(currentFieldName, token, parser)){ - throw new QueryParsingException(parseContext, "[script] filter does not support [" + currentFieldName + "]"); + throw new QueryParsingException(parseContext, "[script] query does not support [" + currentFieldName + "]"); } } } @@ -109,11 +110,11 @@ public class ScriptFilterParser implements FilterParser { params = newHashMap(); } - Filter filter = new ScriptFilter(scriptLang, script, scriptType, params, parseContext.scriptService(), parseContext.lookup()); - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); + Query query = new ScriptFilter(scriptLang, script, scriptType, params, parseContext.scriptService(), parseContext.lookup()); + if (queryName != null) { + parseContext.addNamedQuery(queryName, query); } - return filter; + return query; } public static class ScriptFilter extends Filter { diff --git a/src/main/java/org/elasticsearch/index/query/TermFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/TermFilterBuilder.java deleted file mode 100644 index 3ca5069127d..00000000000 --- a/src/main/java/org/elasticsearch/index/query/TermFilterBuilder.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.common.xcontent.XContentBuilder; - -import java.io.IOException; - -/** - * A filter for a field based on a term. - * - * - */ -public class TermFilterBuilder extends BaseFilterBuilder { - - private final String name; - - private final Object value; - - private String filterName; - - /** - * A filter for a field based on a term. - * - * @param name The field name - * @param value The term value - */ - public TermFilterBuilder(String name, String value) { - this(name, (Object) value); - } - - /** - * A filter for a field based on a term. - * - * @param name The field name - * @param value The term value - */ - public TermFilterBuilder(String name, int value) { - this(name, (Object) value); - } - - /** - * A filter for a field based on a term. - * - * @param name The field name - * @param value The term value - */ - public TermFilterBuilder(String name, long value) { - this(name, (Object) value); - } - - /** - * A filter for a field based on a term. - * - * @param name The field name - * @param value The term value - */ - public TermFilterBuilder(String name, float value) { - this(name, (Object) value); - } - - /** - * A filter for a field based on a term. - * - * @param name The field name - * @param value The term value - */ - public TermFilterBuilder(String name, double value) { - this(name, (Object) value); - } - - /** - * A filter for a field based on a term. - * - * @param name The field name - * @param value The term value - */ - public TermFilterBuilder(String name, Object value) { - this.name = name; - this.value = value; - } - - /** - * Sets the filter name for the filter that can be used when searching for matched_filters per hit. - */ - public TermFilterBuilder filterName(String filterName) { - this.filterName = filterName; - return this; - } - - @Override - public void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(TermFilterParser.NAME); - builder.field(name, value); - if (filterName != null) { - builder.field("_name", filterName); - } - builder.endObject(); - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/TermFilterParser.java b/src/main/java/org/elasticsearch/index/query/TermFilterParser.java deleted file mode 100644 index 0224a6384da..00000000000 --- a/src/main/java/org/elasticsearch/index/query/TermFilterParser.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.apache.lucene.index.Term; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.QueryWrapperFilter; -import org.apache.lucene.search.TermQuery; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.lucene.BytesRefs; -import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.mapper.MapperService; - -import java.io.IOException; - -/** - * - */ -public class TermFilterParser implements FilterParser { - - public static final String NAME = "term"; - - @Inject - public TermFilterParser() { - } - - @Override - public String[] names() { - return new String[]{NAME}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - String fieldName = null; - Object value = null; - - String filterName = null; - String currentFieldName = null; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (parseContext.isDeprecatedSetting(currentFieldName)) { - // skip - } else if (token == XContentParser.Token.START_OBJECT) { - // also support a format of "term" : {"field_name" : { ... }} - fieldName = currentFieldName; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else { - if ("term".equals(currentFieldName)) { - value = parser.objectBytes(); - } else if ("value".equals(currentFieldName)) { - value = parser.objectBytes(); - } else if ("_name".equals(currentFieldName)) { - filterName = parser.text(); - } else { - throw new QueryParsingException(parseContext, "[term] filter does not support [" + currentFieldName + "]"); - } - } - } - } else if (token.isValue()) { - if ("_name".equals(currentFieldName)) { - filterName = parser.text(); - } else { - fieldName = currentFieldName; - value = parser.objectBytes(); - } - } - } - - if (fieldName == null) { - throw new QueryParsingException(parseContext, "No field specified for term filter"); - } - - if (value == null) { - throw new QueryParsingException(parseContext, "No value specified for term filter"); - } - - Filter filter = null; - MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); - if (smartNameFieldMappers != null && smartNameFieldMappers.hasMapper()) { - filter = smartNameFieldMappers.mapper().termFilter(value, parseContext); - } - if (filter == null) { - filter = new QueryWrapperFilter(new TermQuery(new Term(fieldName, BytesRefs.toBytesRef(value)))); - } - - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); - } - return filter; - } -} diff --git a/src/main/java/org/elasticsearch/index/query/TermQueryParser.java b/src/main/java/org/elasticsearch/index/query/TermQueryParser.java index 3a913fc21ad..a760a041b1c 100644 --- a/src/main/java/org/elasticsearch/index/query/TermQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/TermQueryParser.java @@ -49,40 +49,47 @@ public class TermQueryParser implements QueryParser { public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); - XContentParser.Token token = parser.nextToken(); - if (token != XContentParser.Token.FIELD_NAME) { - throw new QueryParsingException(parseContext, "[term] query malformed, no field"); - } - String fieldName = parser.currentName(); - String queryName = null; + String fieldName = null; Object value = null; float boost = 1.0f; - token = parser.nextToken(); - if (token == XContentParser.Token.START_OBJECT) { - String currentFieldName = null; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else { - if ("term".equals(currentFieldName)) { - value = parser.objectBytes(); - } else if ("value".equals(currentFieldName)) { - value = parser.objectBytes(); - } else if ("boost".equals(currentFieldName)) { - boost = parser.floatValue(); - } else if ("_name".equals(currentFieldName)) { - queryName = parser.text(); + String currentFieldName = null; + XContentParser.Token token; + while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { + if (token == XContentParser.Token.FIELD_NAME) { + currentFieldName = parser.currentName(); + } else if (parseContext.isDeprecatedSetting(currentFieldName)) { + // skip + } else if (token == XContentParser.Token.START_OBJECT) { + // also support a format of "term" : {"field_name" : { ... }} + fieldName = currentFieldName; + while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { + if (token == XContentParser.Token.FIELD_NAME) { + currentFieldName = parser.currentName(); } else { - throw new QueryParsingException(parseContext, "[term] query does not support [" + currentFieldName + "]"); + if ("term".equals(currentFieldName)) { + value = parser.objectBytes(); + } else if ("value".equals(currentFieldName)) { + value = parser.objectBytes(); + } else if ("_name".equals(currentFieldName)) { + queryName = parser.text(); + } else if ("boost".equals(currentFieldName)) { + boost = parser.floatValue(); + } else { + throw new QueryParsingException(parseContext, "[term] query does not support [" + currentFieldName + "]"); + } } } + } else if (token.isValue()) { + if ("_name".equals(currentFieldName)) { + queryName = parser.text(); + } else if ("boost".equals(currentFieldName)) { + boost = parser.floatValue(); + } else { + fieldName = currentFieldName; + value = parser.objectBytes(); + } } - parser.nextToken(); - } else { - value = parser.text(); - // move to the next token - parser.nextToken(); } if (value == null) { diff --git a/src/main/java/org/elasticsearch/index/query/TermsFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/TermsFilterBuilder.java deleted file mode 100644 index d753235e341..00000000000 --- a/src/main/java/org/elasticsearch/index/query/TermsFilterBuilder.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.common.xcontent.XContentBuilder; - -import java.io.IOException; - -/** - * A filer for a field based on several terms matching on any of them. - */ -public class TermsFilterBuilder extends BaseFilterBuilder { - - private final String name; - - private final Object values; - - private String filterName; - - private String execution; - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public TermsFilterBuilder(String name, String... values) { - this(name, (Object[]) values); - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public TermsFilterBuilder(String name, int... values) { - this.name = name; - this.values = values; - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public TermsFilterBuilder(String name, long... values) { - this.name = name; - this.values = values; - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public TermsFilterBuilder(String name, float... values) { - this.name = name; - this.values = values; - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public TermsFilterBuilder(String name, double... values) { - this.name = name; - this.values = values; - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public TermsFilterBuilder(String name, Object... values) { - this.name = name; - this.values = values; - } - - /** - * A filer for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public TermsFilterBuilder(String name, Iterable values) { - this.name = name; - this.values = values; - } - - /** - * Sets the execution mode for the terms filter. Cane be either "plain", "bool" - * "and". Defaults to "plain". - * @deprecated elasticsearch now makes better decisions on its own - */ - @Deprecated - public TermsFilterBuilder execution(String execution) { - this.execution = execution; - return this; - } - - /** - * Sets the filter name for the filter that can be used when searching for matched_filters per hit. - */ - public TermsFilterBuilder filterName(String filterName) { - this.filterName = filterName; - return this; - } - - @Override - public void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(TermsFilterParser.NAME); - builder.field(name, values); - - if (execution != null) { - builder.field("execution", execution); - } - - if (filterName != null) { - builder.field("_name", filterName); - } - - builder.endObject(); - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/TermsFilterParser.java b/src/main/java/org/elasticsearch/index/query/TermsFilterParser.java deleted file mode 100644 index ce8a8122665..00000000000 --- a/src/main/java/org/elasticsearch/index/query/TermsFilterParser.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import com.google.common.collect.Lists; - -import org.apache.lucene.queries.TermsQuery; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.QueryWrapperFilter; -import org.apache.lucene.util.BytesRef; -import org.elasticsearch.action.get.GetRequest; -import org.elasticsearch.action.get.GetResponse; -import org.elasticsearch.client.Client; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.lucene.BytesRefs; -import org.elasticsearch.common.lucene.search.Queries; -import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.common.xcontent.support.XContentMapValues; -import org.elasticsearch.index.mapper.FieldMapper; -import org.elasticsearch.index.mapper.MapperService; -import org.elasticsearch.indices.cache.filter.terms.TermsLookup; - -import java.io.IOException; -import java.util.List; - -/** - * - */ -public class TermsFilterParser implements FilterParser { - - public static final String NAME = "terms"; - private Client client; - - @Deprecated - public static final String EXECUTION_KEY = "execution"; - - @Inject - public TermsFilterParser() { - } - - @Override - public String[] names() { - return new String[]{NAME, "in"}; - } - - @Inject(optional = true) - public void setClient(Client client) { - this.client = client; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - MapperService.SmartNameFieldMappers smartNameFieldMappers; - String filterName = null; - String currentFieldName = null; - - String lookupIndex = parseContext.index().name(); - String lookupType = null; - String lookupId = null; - String lookupPath = null; - String lookupRouting = null; - - XContentParser.Token token; - List terms = Lists.newArrayList(); - String fieldName = null; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (parseContext.isDeprecatedSetting(currentFieldName)) { - // skip - } else if (token == XContentParser.Token.START_ARRAY) { - if (fieldName != null) { - throw new QueryParsingException(parseContext, "[terms] filter does not support multiple fields"); - } - fieldName = currentFieldName; - - while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - Object value = parser.objectBytes(); - if (value == null) { - throw new QueryParsingException(parseContext, "No value specified for terms filter"); - } - terms.add(value); - } - } else if (token == XContentParser.Token.START_OBJECT) { - fieldName = currentFieldName; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (token.isValue()) { - if ("index".equals(currentFieldName)) { - lookupIndex = parser.text(); - } else if ("type".equals(currentFieldName)) { - lookupType = parser.text(); - } else if ("id".equals(currentFieldName)) { - lookupId = parser.text(); - } else if ("path".equals(currentFieldName)) { - lookupPath = parser.text(); - } else if ("routing".equals(currentFieldName)) { - lookupRouting = parser.textOrNull(); - } else { - throw new QueryParsingException(parseContext, "[terms] filter does not support [" + currentFieldName - + "] within lookup element"); - } - } - } - if (lookupType == null) { - throw new QueryParsingException(parseContext, "[terms] filter lookup element requires specifying the type"); - } - if (lookupId == null) { - throw new QueryParsingException(parseContext, "[terms] filter lookup element requires specifying the id"); - } - if (lookupPath == null) { - throw new QueryParsingException(parseContext, "[terms] filter lookup element requires specifying the path"); - } - } else if (token.isValue()) { - if (EXECUTION_KEY.equals(currentFieldName)) { - // ignore - } else if ("_name".equals(currentFieldName)) { - filterName = parser.text(); - } else { - throw new QueryParsingException(parseContext, "[terms] filter does not support [" + currentFieldName + "]"); - } - } - } - - if (fieldName == null) { - throw new QueryParsingException(parseContext, "terms filter requires a field name, followed by array of terms"); - } - - FieldMapper fieldMapper = null; - smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); - if (smartNameFieldMappers != null) { - if (smartNameFieldMappers.hasMapper()) { - fieldMapper = smartNameFieldMappers.mapper(); - fieldName = fieldMapper.names().indexName(); - } - } - - if (lookupId != null) { - final TermsLookup lookup = new TermsLookup(lookupIndex, lookupType, lookupId, lookupRouting, lookupPath, parseContext); - final GetResponse getResponse = client.get(new GetRequest(lookup.getIndex(), lookup.getType(), lookup.getId()).preference("_local").routing(lookup.getRouting())).actionGet(); - if (getResponse.isExists()) { - List values = XContentMapValues.extractRawValues(lookup.getPath(), getResponse.getSourceAsMap()); - terms.addAll(values); - } - } - - if (terms.isEmpty()) { - return Queries.newMatchNoDocsFilter(); - } - - Filter filter; - if (fieldMapper != null) { - filter = fieldMapper.termsFilter(terms, parseContext); - } else { - BytesRef[] filterValues = new BytesRef[terms.size()]; - for (int i = 0; i < filterValues.length; i++) { - filterValues[i] = BytesRefs.toBytesRef(terms.get(i)); - } - filter = new QueryWrapperFilter(new TermsQuery(fieldName, filterValues)); - } - - if (filterName != null) { - parseContext.addNamedFilter(filterName, filter); - } - return filter; - } -} diff --git a/src/main/java/org/elasticsearch/index/query/TermsLookupFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/TermsLookupQueryBuilder.java similarity index 77% rename from src/main/java/org/elasticsearch/index/query/TermsLookupFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/TermsLookupQueryBuilder.java index 1a9473ede40..abffc4fa442 100644 --- a/src/main/java/org/elasticsearch/index/query/TermsLookupFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/TermsLookupQueryBuilder.java @@ -26,7 +26,7 @@ import java.io.IOException; /** * A filer for a field based on several terms matching on any of them. */ -public class TermsLookupFilterBuilder extends BaseFilterBuilder { +public class TermsLookupQueryBuilder extends BaseQueryBuilder { private final String name; private String lookupIndex; @@ -36,24 +36,24 @@ public class TermsLookupFilterBuilder extends BaseFilterBuilder { private String lookupPath; private Boolean lookupCache; - private String filterName; + private String queryName; - public TermsLookupFilterBuilder(String name) { + public TermsLookupQueryBuilder(String name) { this.name = name; } /** * Sets the filter name for the filter that can be used when searching for matched_filters per hit. */ - public TermsLookupFilterBuilder filterName(String filterName) { - this.filterName = filterName; + public TermsLookupQueryBuilder queryName(String queryName) { + this.queryName = queryName; return this; } /** * Sets the index name to lookup the terms from. */ - public TermsLookupFilterBuilder lookupIndex(String lookupIndex) { + public TermsLookupQueryBuilder lookupIndex(String lookupIndex) { this.lookupIndex = lookupIndex; return this; } @@ -61,7 +61,7 @@ public class TermsLookupFilterBuilder extends BaseFilterBuilder { /** * Sets the index type to lookup the terms from. */ - public TermsLookupFilterBuilder lookupType(String lookupType) { + public TermsLookupQueryBuilder lookupType(String lookupType) { this.lookupType = lookupType; return this; } @@ -69,7 +69,7 @@ public class TermsLookupFilterBuilder extends BaseFilterBuilder { /** * Sets the doc id to lookup the terms from. */ - public TermsLookupFilterBuilder lookupId(String lookupId) { + public TermsLookupQueryBuilder lookupId(String lookupId) { this.lookupId = lookupId; return this; } @@ -77,24 +77,24 @@ public class TermsLookupFilterBuilder extends BaseFilterBuilder { /** * Sets the path within the document to lookup the terms from. */ - public TermsLookupFilterBuilder lookupPath(String lookupPath) { + public TermsLookupQueryBuilder lookupPath(String lookupPath) { this.lookupPath = lookupPath; return this; } - public TermsLookupFilterBuilder lookupRouting(String lookupRouting) { + public TermsLookupQueryBuilder lookupRouting(String lookupRouting) { this.lookupRouting = lookupRouting; return this; } - public TermsLookupFilterBuilder lookupCache(boolean lookupCache) { + public TermsLookupQueryBuilder lookupCache(boolean lookupCache) { this.lookupCache = lookupCache; return this; } @Override public void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(TermsFilterParser.NAME); + builder.startObject(TermsQueryParser.NAME); builder.startObject(name); if (lookupIndex != null) { @@ -111,8 +111,8 @@ public class TermsLookupFilterBuilder extends BaseFilterBuilder { builder.field("path", lookupPath); builder.endObject(); - if (filterName != null) { - builder.field("_name", filterName); + if (queryName != null) { + builder.field("_name", queryName); } builder.endObject(); diff --git a/src/main/java/org/elasticsearch/index/query/TermsQueryBuilder.java b/src/main/java/org/elasticsearch/index/query/TermsQueryBuilder.java index a18b3a858b9..885ecac5e2d 100644 --- a/src/main/java/org/elasticsearch/index/query/TermsQueryBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/TermsQueryBuilder.java @@ -16,32 +16,28 @@ * specific language governing permissions and limitations * under the License. */ + package org.elasticsearch.index.query; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; -import java.util.Collection; /** - * + * A filer for a field based on several terms matching on any of them. */ -public class TermsQueryBuilder extends BaseQueryBuilder implements BoostableQueryBuilder { +public class TermsQueryBuilder extends BaseQueryBuilder { private final String name; - private final Object[] values; - - private String minimumShouldMatch; - - private Boolean disableCoord; - - private float boost = -1; + private final Object values; private String queryName; + private String execution; + /** - * A query for a field based on several terms matching on any of them. + * A filer for a field based on several terms matching on any of them. * * @param name The field name * @param values The terms @@ -51,63 +47,51 @@ public class TermsQueryBuilder extends BaseQueryBuilder implements BoostableQuer } /** - * A query for a field based on several terms matching on any of them. + * A filer for a field based on several terms matching on any of them. * * @param name The field name * @param values The terms */ public TermsQueryBuilder(String name, int... values) { this.name = name; - this.values = new Integer[values.length]; - for (int i = 0; i < values.length; i++) { - this.values[i] = values[i]; - } + this.values = values; } /** - * A query for a field based on several terms matching on any of them. + * A filer for a field based on several terms matching on any of them. * * @param name The field name * @param values The terms */ public TermsQueryBuilder(String name, long... values) { this.name = name; - this.values = new Long[values.length]; - for (int i = 0; i < values.length; i++) { - this.values[i] = values[i]; - } + this.values = values; } /** - * A query for a field based on several terms matching on any of them. + * A filer for a field based on several terms matching on any of them. * * @param name The field name * @param values The terms */ public TermsQueryBuilder(String name, float... values) { this.name = name; - this.values = new Float[values.length]; - for (int i = 0; i < values.length; i++) { - this.values[i] = values[i]; - } + this.values = values; } /** - * A query for a field based on several terms matching on any of them. + * A filer for a field based on several terms matching on any of them. * * @param name The field name * @param values The terms */ public TermsQueryBuilder(String name, double... values) { this.name = name; - this.values = new Double[values.length]; - for (int i = 0; i < values.length; i++) { - this.values[i] = values[i]; - } + this.values = values; } /** - * A query for a field based on several terms matching on any of them. + * A filer for a field based on several terms matching on any of them. * * @param name The field name * @param values The terms @@ -117,49 +101,30 @@ public class TermsQueryBuilder extends BaseQueryBuilder implements BoostableQuer this.values = values; } - /** - * A query for a field based on several terms matching on any of them. - * - * @param name The field name - * @param values The terms - */ - public TermsQueryBuilder(String name, Collection values) { - this(name, values.toArray()); - } - /** - * Sets the minimum number of matches across the provided terms. Defaults to 1. + * A filer for a field based on several terms matching on any of them. + * + * @param name The field name + * @param values The terms */ - public TermsQueryBuilder minimumMatch(int minimumMatch) { - this.minimumShouldMatch = Integer.toString(minimumMatch); - return this; - } - - public TermsQueryBuilder minimumShouldMatch(String minimumShouldMatch) { - this.minimumShouldMatch = minimumShouldMatch; - return this; + public TermsQueryBuilder(String name, Iterable values) { + this.name = name; + this.values = values; } /** - * Sets the boost for this query. Documents matching this query will (in addition to the normal - * weightings) have their score multiplied by the boost provided. + * Sets the execution mode for the terms filter. Cane be either "plain", "bool" + * "and". Defaults to "plain". + * @deprecated elasticsearch now makes better decisions on its own */ - @Override - public TermsQueryBuilder boost(float boost) { - this.boost = boost; + @Deprecated + public TermsQueryBuilder execution(String execution) { + this.execution = execution; return this; } /** - * Disables Similarity#coord(int,int) in scoring. Defualts to false. - */ - public TermsQueryBuilder disableCoord(boolean disableCoord) { - this.disableCoord = disableCoord; - return this; - } - - /** - * Sets the query name for the filter that can be used when searching for matched_filters per hit. + * Sets the filter name for the filter that can be used when searching for matched_filters per hit. */ public TermsQueryBuilder queryName(String queryName) { this.queryName = queryName; @@ -167,27 +132,18 @@ public class TermsQueryBuilder extends BaseQueryBuilder implements BoostableQuer } @Override - protected void doXContent(XContentBuilder builder, Params params) throws IOException { + public void doXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(TermsQueryParser.NAME); - builder.startArray(name); - for (Object value : values) { - builder.value(value); - } - builder.endArray(); + builder.field(name, values); - if (minimumShouldMatch != null) { - builder.field("minimum_should_match", minimumShouldMatch); - } - if (disableCoord != null) { - builder.field("disable_coord", disableCoord); - } - if (boost != -1) { - builder.field("boost", boost); + if (execution != null) { + builder.field("execution", execution); } + if (queryName != null) { builder.field("_name", queryName); } builder.endObject(); } -} +} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/TermsQueryParser.java b/src/main/java/org/elasticsearch/index/query/TermsQueryParser.java index dcf078d19b1..b26c65459a9 100644 --- a/src/main/java/org/elasticsearch/index/query/TermsQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/TermsQueryParser.java @@ -16,37 +16,45 @@ * specific language governing permissions and limitations * under the License. */ + package org.elasticsearch.index.query; +import com.google.common.collect.Lists; + import org.apache.lucene.index.Term; -import org.apache.lucene.search.BooleanClause; +import org.apache.lucene.queries.TermsQuery; +import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; +import org.apache.lucene.util.BytesRef; +import org.elasticsearch.action.get.GetRequest; +import org.elasticsearch.action.get.GetResponse; +import org.elasticsearch.client.Client; +import org.elasticsearch.common.ParseField; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.BytesRefs; import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.xcontent.XContentParser; +import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.MapperService; +import org.elasticsearch.indices.cache.filter.terms.TermsLookup; import java.io.IOException; import java.util.List; -import static com.google.common.collect.Lists.newArrayList; -import static org.elasticsearch.common.lucene.search.Queries.fixNegativeQueryIfNeeded; - /** - *
- * "terms" : {
- *  "field_name" : [ "value1", "value2" ]
- *  "minimum_match" : 1
- * }
- * 
+ * */ public class TermsQueryParser implements QueryParser { public static final String NAME = "terms"; + private static final ParseField MIN_SHOULD_MATCH_FIELD = new ParseField("min_match", "min_should_match").withAllDeprecated("Use [bool] query instead"); + private Client client; + + @Deprecated + public static final String EXECUTION_KEY = "execution"; @Inject public TermsQueryParser() { @@ -54,44 +62,90 @@ public class TermsQueryParser implements QueryParser { @Override public String[] names() { - return new String[]{NAME, "in"}; // allow both "in" and "terms" (since its similar to the "terms" filter) + return new String[]{NAME, "in"}; + } + + @Inject(optional = true) + public void setClient(Client client) { + this.client = client; } @Override public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); - String fieldName = null; - boolean disableCoord = false; - float boost = 1.0f; - String minimumShouldMatch = null; - List values = newArrayList(); + MapperService.SmartNameFieldMappers smartNameFieldMappers; String queryName = null; - String currentFieldName = null; + + String lookupIndex = parseContext.index().name(); + String lookupType = null; + String lookupId = null; + String lookupPath = null; + String lookupRouting = null; + String minShouldMatch = null; + XContentParser.Token token; + List terms = Lists.newArrayList(); + String fieldName = null; + float boost = 1f; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); + } else if (parseContext.isDeprecatedSetting(currentFieldName)) { + // skip } else if (token == XContentParser.Token.START_ARRAY) { if (fieldName != null) { throw new QueryParsingException(parseContext, "[terms] query does not support multiple fields"); } fieldName = currentFieldName; + while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { Object value = parser.objectBytes(); if (value == null) { throw new QueryParsingException(parseContext, "No value specified for terms query"); } - values.add(value); + terms.add(value); + } + } else if (token == XContentParser.Token.START_OBJECT) { + fieldName = currentFieldName; + while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { + if (token == XContentParser.Token.FIELD_NAME) { + currentFieldName = parser.currentName(); + } else if (token.isValue()) { + if ("index".equals(currentFieldName)) { + lookupIndex = parser.text(); + } else if ("type".equals(currentFieldName)) { + lookupType = parser.text(); + } else if ("id".equals(currentFieldName)) { + lookupId = parser.text(); + } else if ("path".equals(currentFieldName)) { + lookupPath = parser.text(); + } else if ("routing".equals(currentFieldName)) { + lookupRouting = parser.textOrNull(); + } else { + throw new QueryParsingException(parseContext, "[terms] query does not support [" + currentFieldName + + "] within lookup element"); + } + } + } + if (lookupType == null) { + throw new QueryParsingException(parseContext, "[terms] query lookup element requires specifying the type"); + } + if (lookupId == null) { + throw new QueryParsingException(parseContext, "[terms] query lookup element requires specifying the id"); + } + if (lookupPath == null) { + throw new QueryParsingException(parseContext, "[terms] query lookup element requires specifying the path"); } } else if (token.isValue()) { - if ("disable_coord".equals(currentFieldName) || "disableCoord".equals(currentFieldName)) { - disableCoord = parser.booleanValue(); - } else if ("minimum_match".equals(currentFieldName) || "minimumMatch".equals(currentFieldName)) { - minimumShouldMatch = parser.textOrNull(); - } else if ("minimum_should_match".equals(currentFieldName) || "minimumShouldMatch".equals(currentFieldName)) { - minimumShouldMatch = parser.textOrNull(); + if (EXECUTION_KEY.equals(currentFieldName)) { + // ignore + } else if (MIN_SHOULD_MATCH_FIELD.match(currentFieldName)) { + if (minShouldMatch != null) { + throw new IllegalArgumentException("[" + currentFieldName + "] is not allowed in a filter context for the [" + NAME + "] query"); + } + minShouldMatch = parser.textOrNull(); } else if ("boost".equals(currentFieldName)) { boost = parser.floatValue(); } else if ("_name".equals(currentFieldName)) { @@ -99,38 +153,63 @@ public class TermsQueryParser implements QueryParser { } else { throw new QueryParsingException(parseContext, "[terms] query does not support [" + currentFieldName + "]"); } - } else { - throw new QueryParsingException(parseContext, "[terms] query does not support [" + currentFieldName + "]"); } } if (fieldName == null) { - throw new QueryParsingException(parseContext, "No field specified for terms query"); + throw new QueryParsingException(parseContext, "terms query requires a field name, followed by array of terms"); } - FieldMapper mapper = null; - MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); - String[] previousTypes = null; - if (smartNameFieldMappers != null && smartNameFieldMappers.hasMapper()) { - mapper = smartNameFieldMappers.mapper(); - } - - - BooleanQuery booleanQuery = new BooleanQuery(disableCoord); - for (Object value : values) { - if (mapper != null) { - booleanQuery.add(new BooleanClause(mapper.termQuery(value, parseContext), BooleanClause.Occur.SHOULD)); - } else { - booleanQuery.add(new TermQuery(new Term(fieldName, BytesRefs.toString(value))), BooleanClause.Occur.SHOULD); + FieldMapper fieldMapper = null; + smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); + if (smartNameFieldMappers != null) { + if (smartNameFieldMappers.hasMapper()) { + fieldMapper = smartNameFieldMappers.mapper(); + fieldName = fieldMapper.names().indexName(); } } - booleanQuery.setBoost(boost); - Queries.applyMinimumShouldMatch(booleanQuery, minimumShouldMatch); - Query query = fixNegativeQueryIfNeeded(booleanQuery); + + if (lookupId != null) { + final TermsLookup lookup = new TermsLookup(lookupIndex, lookupType, lookupId, lookupRouting, lookupPath, parseContext); + final GetResponse getResponse = client.get(new GetRequest(lookup.getIndex(), lookup.getType(), lookup.getId()).preference("_local").routing(lookup.getRouting())).actionGet(); + if (getResponse.isExists()) { + List values = XContentMapValues.extractRawValues(lookup.getPath(), getResponse.getSourceAsMap()); + terms.addAll(values); + } + } + + if (terms.isEmpty()) { + return Queries.newMatchNoDocsQuery(); + } + + Query query; + if (parseContext.isFilter()) { + if (fieldMapper != null) { + query = fieldMapper.termsQuery(terms, parseContext); + } else { + BytesRef[] filterValues = new BytesRef[terms.size()]; + for (int i = 0; i < filterValues.length; i++) { + filterValues[i] = BytesRefs.toBytesRef(terms.get(i)); + } + query = new TermsQuery(fieldName, filterValues); + } + } else { + BooleanQuery bq = new BooleanQuery(); + for (Object term : terms) { + if (fieldMapper != null) { + bq.add(fieldMapper.termQuery(term, parseContext), Occur.SHOULD); + } else { + bq.add(new TermQuery(new Term(fieldName, BytesRefs.toBytesRef(term))), Occur.SHOULD); + } + } + Queries.applyMinimumShouldMatch(bq, minShouldMatch); + query = bq; + } + query.setBoost(boost); + if (queryName != null) { parseContext.addNamedQuery(queryName, query); } return query; } } - diff --git a/src/main/java/org/elasticsearch/index/query/TopChildrenQueryParser.java b/src/main/java/org/elasticsearch/index/query/TopChildrenQueryParser.java index 7ca32527b02..fe1e13fcceb 100644 --- a/src/main/java/org/elasticsearch/index/query/TopChildrenQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/TopChildrenQueryParser.java @@ -18,9 +18,7 @@ */ package org.elasticsearch.index.query; -import org.apache.lucene.search.FilteredQuery; import org.apache.lucene.search.Query; -import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.join.BitDocIdSetFilter; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Inject; @@ -131,11 +129,11 @@ public class TopChildrenQueryParser implements QueryParser { innerQuery.setBoost(boost); // wrap the query with type query - innerQuery = new FilteredQuery(innerQuery, childDocMapper.typeFilter()); + innerQuery = Queries.filtered(innerQuery, childDocMapper.typeFilter()); ParentChildIndexFieldData parentChildIndexFieldData = parseContext.getForField(parentFieldMapper); TopChildrenQuery query = new TopChildrenQuery(parentChildIndexFieldData, innerQuery, childType, parentType, scoreType, factor, incrementalFactor, nonNestedDocsFilter); if (queryName != null) { - parseContext.addNamedFilter(queryName, new QueryWrapperFilter(query)); + parseContext.addNamedQuery(queryName, query); } return query; } diff --git a/src/main/java/org/elasticsearch/index/query/TypeFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/TypeQueryBuilder.java similarity index 88% rename from src/main/java/org/elasticsearch/index/query/TypeFilterBuilder.java rename to src/main/java/org/elasticsearch/index/query/TypeQueryBuilder.java index fe939d0ba47..3ce13dac1d6 100644 --- a/src/main/java/org/elasticsearch/index/query/TypeFilterBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/TypeQueryBuilder.java @@ -23,17 +23,17 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; -public class TypeFilterBuilder extends BaseFilterBuilder { +public class TypeQueryBuilder extends BaseQueryBuilder { private final String type; - public TypeFilterBuilder(String type) { + public TypeQueryBuilder(String type) { this.type = type; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(TypeFilterParser.NAME); + builder.startObject(TypeQueryParser.NAME); builder.field("value", type); builder.endObject(); } diff --git a/src/main/java/org/elasticsearch/index/query/TypeFilterParser.java b/src/main/java/org/elasticsearch/index/query/TypeQueryParser.java similarity index 86% rename from src/main/java/org/elasticsearch/index/query/TypeFilterParser.java rename to src/main/java/org/elasticsearch/index/query/TypeQueryParser.java index 6c9e9523e76..e4b7889ca12 100644 --- a/src/main/java/org/elasticsearch/index/query/TypeFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/TypeQueryParser.java @@ -20,8 +20,7 @@ package org.elasticsearch.index.query; import org.apache.lucene.index.Term; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.QueryWrapperFilter; +import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.inject.Inject; @@ -31,12 +30,12 @@ import org.elasticsearch.index.mapper.internal.TypeFieldMapper; import java.io.IOException; -public class TypeFilterParser implements FilterParser { +public class TypeQueryParser implements QueryParser { public static final String NAME = "type"; @Inject - public TypeFilterParser() { + public TypeQueryParser() { } @Override @@ -45,7 +44,7 @@ public class TypeFilterParser implements FilterParser { } @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { + public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); XContentParser.Token token = parser.nextToken(); @@ -64,11 +63,11 @@ public class TypeFilterParser implements FilterParser { // move to the next token parser.nextToken(); - Filter filter; + Query filter; //LUCENE 4 UPGRADE document mapper should use bytesref as well? DocumentMapper documentMapper = parseContext.mapperService().documentMapper(type.utf8ToString()); if (documentMapper == null) { - filter = new QueryWrapperFilter(new TermQuery(new Term(TypeFieldMapper.NAME, type))); + filter = new TermQuery(new Term(TypeFieldMapper.NAME, type)); } else { filter = documentMapper.typeFilter(); } diff --git a/src/main/java/org/elasticsearch/index/query/WrapperFilterBuilder.java b/src/main/java/org/elasticsearch/index/query/WrapperFilterBuilder.java deleted file mode 100644 index 8a63c0a4a16..00000000000 --- a/src/main/java/org/elasticsearch/index/query/WrapperFilterBuilder.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; -/** - * Created by IntelliJ IDEA. - * User: cedric - * Date: 12/07/11 - * Time: 11:30 - */ - -import com.google.common.base.Charsets; -import org.elasticsearch.common.xcontent.XContentBuilder; - -import java.io.IOException; - -/** - * A Filter builder which allows building a filter thanks to a JSON string or binary data. This is useful when you want - * to use the Java Builder API but still have JSON filter strings at hand that you want to combine with other - * query builders. - */ -public class WrapperFilterBuilder extends BaseFilterBuilder { - - private final byte[] source; - private final int offset; - private final int length; - - public WrapperFilterBuilder(String source) { - this.source = source.getBytes(Charsets.UTF_8); - this.offset = 0; - this.length = this.source.length; - } - - public WrapperFilterBuilder(byte[] source, int offset, int length) { - this.source = source; - this.offset = offset; - this.length = length; - } - - @Override - protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(WrapperFilterParser.NAME); - builder.field("filter", source, offset, length); - builder.endObject(); - } -} diff --git a/src/main/java/org/elasticsearch/index/query/WrapperFilterParser.java b/src/main/java/org/elasticsearch/index/query/WrapperFilterParser.java deleted file mode 100644 index 35ca8724453..00000000000 --- a/src/main/java/org/elasticsearch/index/query/WrapperFilterParser.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.apache.lucene.search.Filter; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.common.xcontent.XContentParser; - -import java.io.IOException; - -/** - * Filter parser for embedded filter. - */ -public class WrapperFilterParser implements FilterParser { - - public static final String NAME = "wrapper"; - - @Inject - public WrapperFilterParser() { - } - - @Override - public String[] names() { - return new String[]{NAME}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - XContentParser.Token token = parser.nextToken(); - if (token != XContentParser.Token.FIELD_NAME) { - throw new QueryParsingException(parseContext, "[wrapper] filter malformed"); - } - String fieldName = parser.currentName(); - if (!fieldName.equals("filter")) { - throw new QueryParsingException(parseContext, "[wrapper] filter malformed"); - } - parser.nextToken(); - - byte[] querySource = parser.binaryValue(); - try (XContentParser qSourceParser = XContentFactory.xContent(querySource).createParser(querySource)) { - final QueryParseContext context = new QueryParseContext(parseContext.index(), parseContext.indexQueryParserService()); - context.reset(qSourceParser); - Filter result = context.parseInnerFilter(); - parser.nextToken(); - parseContext.combineNamedFilters(context); - return result; - } - } -} diff --git a/src/main/java/org/elasticsearch/index/query/functionscore/FunctionScoreQueryBuilder.java b/src/main/java/org/elasticsearch/index/query/functionscore/FunctionScoreQueryBuilder.java index f7856462bfa..966d85e183f 100644 --- a/src/main/java/org/elasticsearch/index/query/functionscore/FunctionScoreQueryBuilder.java +++ b/src/main/java/org/elasticsearch/index/query/functionscore/FunctionScoreQueryBuilder.java @@ -23,7 +23,6 @@ import org.elasticsearch.common.lucene.search.function.CombineFunction; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.BaseQueryBuilder; import org.elasticsearch.index.query.BoostableQueryBuilder; -import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.QueryBuilder; import java.io.IOException; @@ -37,7 +36,7 @@ public class FunctionScoreQueryBuilder extends BaseQueryBuilder implements Boost private final QueryBuilder queryBuilder; - private final FilterBuilder filterBuilder; + private final QueryBuilder filterBuilder; private Float boost; @@ -47,7 +46,7 @@ public class FunctionScoreQueryBuilder extends BaseQueryBuilder implements Boost private String boostMode; - private ArrayList filters = new ArrayList<>(); + private ArrayList filters = new ArrayList<>(); private ArrayList scoreFunctions = new ArrayList<>(); private Float minScore = null; @@ -62,29 +61,6 @@ public class FunctionScoreQueryBuilder extends BaseQueryBuilder implements Boost this.filterBuilder = null; } - /** - * Creates a function_score query that executes on documents that match query a query. - * Query and filter will be wrapped into a filtered_query. - * - * @param filterBuilder the filter that defines which documents the function_score query will be executed on. - */ - public FunctionScoreQueryBuilder(FilterBuilder filterBuilder) { - this.filterBuilder = filterBuilder; - this.queryBuilder = null; - } - - /** - * Creates a function_score query that executes on documents that match query and filter. - * Query and filter will be wrapped into a filtered_query. - * - * @param queryBuilder a query that will; be wrapped in a filtered query. - * @param filterBuilder the filter for the filtered query. - */ - public FunctionScoreQueryBuilder(QueryBuilder queryBuilder, FilterBuilder filterBuilder) { - this.filterBuilder = filterBuilder; - this.queryBuilder = queryBuilder; - } - public FunctionScoreQueryBuilder() { this.filterBuilder = null; this.queryBuilder = null; @@ -111,7 +87,7 @@ public class FunctionScoreQueryBuilder extends BaseQueryBuilder implements Boost * @param filter the filter that defines which documents the function_score query will be executed on. * @param scoreFunctionBuilder score function that is executed */ - public FunctionScoreQueryBuilder add(FilterBuilder filter, ScoreFunctionBuilder scoreFunctionBuilder) { + public FunctionScoreQueryBuilder add(QueryBuilder filter, ScoreFunctionBuilder scoreFunctionBuilder) { if (scoreFunctionBuilder == null) { throw new IllegalArgumentException("function_score: function must not be null"); } diff --git a/src/main/java/org/elasticsearch/index/query/functionscore/FunctionScoreQueryParser.java b/src/main/java/org/elasticsearch/index/query/functionscore/FunctionScoreQueryParser.java index 734ab2f7759..a747d98a439 100644 --- a/src/main/java/org/elasticsearch/index/query/functionscore/FunctionScoreQueryParser.java +++ b/src/main/java/org/elasticsearch/index/query/functionscore/FunctionScoreQueryParser.java @@ -22,9 +22,9 @@ package org.elasticsearch.index.query.functionscore; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; +import org.apache.lucene.search.BooleanClause.Occur; +import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.ConstantScoreQuery; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.FilteredQuery; import org.apache.lucene.search.Query; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.ParseField; @@ -58,6 +58,7 @@ public class FunctionScoreQueryParser implements QueryParser { static final String MISPLACED_BOOST_FUNCTION_MESSAGE_SUFFIX = " Did you mean \"boost\" instead?"; public static final ParseField WEIGHT_FIELD = new ParseField("weight"); + private static final ParseField FILTER_FIELD = new ParseField("filter").withAllDeprecated("query"); @Inject public FunctionScoreQueryParser(ScoreFunctionParserMapper functionParserMapper) { @@ -85,7 +86,7 @@ public class FunctionScoreQueryParser implements QueryParser { XContentParser parser = parseContext.parser(); Query query = null; - Filter filter = null; + Query filter = null; float boost = 1.0f; FiltersFunctionScoreQuery.ScoreMode scoreMode = FiltersFunctionScoreQuery.ScoreMode.Multiply; @@ -106,7 +107,7 @@ public class FunctionScoreQueryParser implements QueryParser { currentFieldName = parser.currentName(); } else if ("query".equals(currentFieldName)) { query = parseContext.parseInnerQuery(); - } else if ("filter".equals(currentFieldName)) { + } else if (FILTER_FIELD.match(currentFieldName)) { filter = parseContext.parseInnerFilter(); } else if ("score_mode".equals(currentFieldName) || "scoreMode".equals(currentFieldName)) { scoreMode = parseScoreMode(parseContext, parser); @@ -154,7 +155,10 @@ public class FunctionScoreQueryParser implements QueryParser { } else if (query == null && filter != null) { query = new ConstantScoreQuery(filter); } else if (query != null && filter != null) { - query = new FilteredQuery(query, filter); + final BooleanQuery filtered = new BooleanQuery(); + filtered.add(query, Occur.MUST); + filtered.add(filter, Occur.FILTER); + query = filtered; } // if all filter elements returned null, just use the query if (filterFunctions.isEmpty() && combineFunction == null) { @@ -198,7 +202,7 @@ public class FunctionScoreQueryParser implements QueryParser { ArrayList filterFunctions, String currentFieldName) throws IOException { XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - Filter filter = null; + Query filter = null; ScoreFunction scoreFunction = null; Float functionWeight = null; if (token != XContentParser.Token.START_OBJECT) { @@ -227,7 +231,7 @@ public class FunctionScoreQueryParser implements QueryParser { } } if (filter == null) { - filter = Queries.newMatchAllFilter(); + filter = Queries.newMatchAllQuery(); } if (scoreFunction == null) { throw new ElasticsearchParseException("function_score: One entry in functions list is missing a function."); diff --git a/src/main/java/org/elasticsearch/index/query/support/NestedInnerQueryParseSupport.java b/src/main/java/org/elasticsearch/index/query/support/NestedInnerQueryParseSupport.java index c96fdb7e103..b716fa2db41 100644 --- a/src/main/java/org/elasticsearch/index/query/support/NestedInnerQueryParseSupport.java +++ b/src/main/java/org/elasticsearch/index/query/support/NestedInnerQueryParseSupport.java @@ -19,7 +19,6 @@ package org.elasticsearch.index.query.support; -import org.apache.lucene.search.Filter; import org.apache.lucene.search.Query; import org.apache.lucene.search.join.BitDocIdSetFilter; import org.elasticsearch.common.bytes.BytesReference; @@ -47,7 +46,7 @@ public class NestedInnerQueryParseSupport { private BytesReference source; private Query innerQuery; - private Filter innerFilter; + private Query innerFilter; protected String path; private boolean filterParsed = false; @@ -130,7 +129,7 @@ public class NestedInnerQueryParseSupport { } } - public Filter getInnerFilter() throws IOException { + public Query getInnerFilter() throws IOException { if (filterParsed) { return innerFilter; } else { diff --git a/src/main/java/org/elasticsearch/index/query/support/XContentStructure.java b/src/main/java/org/elasticsearch/index/query/support/XContentStructure.java index ac5de596b9f..37716d12154 100644 --- a/src/main/java/org/elasticsearch/index/query/support/XContentStructure.java +++ b/src/main/java/org/elasticsearch/index/query/support/XContentStructure.java @@ -19,8 +19,6 @@ package org.elasticsearch.index.query.support; -import org.apache.lucene.search.ConstantScoreQuery; -import org.apache.lucene.search.Filter; import org.apache.lucene.search.Query; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.bytes.BytesReference; @@ -97,29 +95,6 @@ public abstract class XContentStructure { } } - /** - * Use the captured bytes to parse the inner filter using the specified - * types. The original QueryParseContext's parser is switched during this - * parsing, so this method is NOT thread-safe. - * @param types types to be used during the inner filter parsing - * @return {@link XConstantScoreQuery} wrapping the filter parsed from the bytes captured in {@code freeze()} - */ - public Query asFilter(String... types) throws IOException { - BytesReference br = this.bytes(); - assert br != null : "innerBytes must be set with .bytes(bytes) or .freeze() before parsing"; - XContentParser innerParser = XContentHelper.createParser(br); - String[] origTypes = QueryParseContext.setTypesWithPrevious(types); - XContentParser old = parseContext.parser(); - parseContext.parser(innerParser); - try { - Filter innerFilter = parseContext.parseInnerFilter(); - return new ConstantScoreQuery(innerFilter); - } finally { - parseContext.parser(old); - QueryParseContext.setTypes(origTypes); - } - } - /** * InnerQuery is an extension of {@code XContentStructure} that eagerly * parses the query in a streaming manner if the types are available at @@ -158,46 +133,4 @@ public abstract class XContentStructure { } } - /** - * InnerFilter is an extension of {@code XContentStructure} that eagerly - * parses the filter in a streaming manner if the types are available at - * construction time. - */ - public static class InnerFilter extends XContentStructure { - private Query query = null; - private boolean queryParsed = false; - - - public InnerFilter(QueryParseContext parseContext1, @Nullable String... types) throws IOException { - super(parseContext1); - if (types != null) { - String[] origTypes = QueryParseContext.setTypesWithPrevious(types); - try { - Filter innerFilter = parseContext1.parseInnerFilter(); - query = new ConstantScoreQuery(innerFilter); - queryParsed = true; - } finally { - QueryParseContext.setTypes(origTypes); - } - } else { - BytesReference innerBytes = XContentFactory.smileBuilder().copyCurrentStructure(parseContext1.parser()).bytes(); - super.bytes(innerBytes); - } - } - - /** - * Return the filter as an - * {@link org.elasticsearch.common.lucene.search.XConstantScoreQuery} - * represented by the XContentStructure object, - * returning the cached Query if it has already been parsed. - * @param types types to be used during the inner filter parsing - */ - @Override - public Query asFilter(String... types) throws IOException { - if (!queryParsed) { // query can be null - this.query = super.asFilter(types); - } - return this.query; - } - } } diff --git a/src/main/java/org/elasticsearch/index/search/FieldDataTermsFilter.java b/src/main/java/org/elasticsearch/index/search/FieldDataTermsFilter.java deleted file mode 100644 index b44bde505c4..00000000000 --- a/src/main/java/org/elasticsearch/index/search/FieldDataTermsFilter.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.elasticsearch.index.search; - -import java.io.IOException; -import java.util.Objects; - -import com.carrotsearch.hppc.DoubleOpenHashSet; -import com.carrotsearch.hppc.LongOpenHashSet; -import com.carrotsearch.hppc.ObjectOpenHashSet; - -import org.apache.lucene.index.LeafReaderContext; -import org.apache.lucene.index.SortedNumericDocValues; -import org.apache.lucene.search.DocIdSet; -import org.apache.lucene.search.DocValuesDocIdSet; -import org.apache.lucene.search.Filter; -import org.apache.lucene.util.Bits; -import org.apache.lucene.util.BytesRef; -import org.elasticsearch.index.fielddata.IndexFieldData; -import org.elasticsearch.index.fielddata.IndexNumericFieldData; -import org.elasticsearch.index.fielddata.SortedBinaryDocValues; -import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; - -/** - * Similar to a {@link org.apache.lucene.queries.TermsFilter} but pulls terms from the fielddata. - */ -public abstract class FieldDataTermsFilter extends Filter { - - final IndexFieldData fieldData; - - protected FieldDataTermsFilter(IndexFieldData fieldData) { - this.fieldData = fieldData; - } - - /** - * Get a {@link FieldDataTermsFilter} that filters on non-numeric terms found in a hppc {@link ObjectOpenHashSet} of - * {@link BytesRef}. - * - * @param fieldData The fielddata for the field. - * @param terms An {@link ObjectOpenHashSet} of terms. - * @return the filter. - */ - public static FieldDataTermsFilter newBytes(IndexFieldData fieldData, ObjectOpenHashSet terms) { - return new BytesFieldDataFilter(fieldData, terms); - } - - /** - * Get a {@link FieldDataTermsFilter} that filters on non-floating point numeric terms found in a hppc - * {@link LongOpenHashSet}. - * - * @param fieldData The fielddata for the field. - * @param terms A {@link LongOpenHashSet} of terms. - * @return the filter. - */ - public static FieldDataTermsFilter newLongs(IndexNumericFieldData fieldData, LongOpenHashSet terms) { - return new LongsFieldDataFilter(fieldData, terms); - } - - /** - * Get a {@link FieldDataTermsFilter} that filters on floating point numeric terms found in a hppc - * {@link DoubleOpenHashSet}. - * - * @param fieldData The fielddata for the field. - * @param terms A {@link DoubleOpenHashSet} of terms. - * @return the filter. - */ - public static FieldDataTermsFilter newDoubles(IndexNumericFieldData fieldData, DoubleOpenHashSet terms) { - return new DoublesFieldDataFilter(fieldData, terms); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (super.equals(obj) == false) return false; - - FieldDataTermsFilter that = (FieldDataTermsFilter) obj; - if (!fieldData.getFieldNames().indexName().equals(that.fieldData.getFieldNames().indexName())) return false; - return true; - } - - @Override - public int hashCode() { - int h = super.hashCode(); - h = 31 * h + fieldData.getFieldNames().indexName().hashCode(); - return h; - } - - /** - * Filters on non-numeric fields. - */ - protected static class BytesFieldDataFilter extends FieldDataTermsFilter { - - final ObjectOpenHashSet terms; - - protected BytesFieldDataFilter(IndexFieldData fieldData, ObjectOpenHashSet terms) { - super(fieldData); - this.terms = terms; - } - - @Override - public boolean equals(Object obj) { - if (super.equals(obj) == false) { - return false; - } - return Objects.equals(terms, ((BytesFieldDataFilter) obj).terms); - } - - @Override - public int hashCode() { - return 31 * super.hashCode() + Objects.hashCode(terms); - } - - @Override - public String toString(String field) { - final StringBuilder sb = new StringBuilder("BytesFieldDataFilter:"); - return sb - .append(fieldData.getFieldNames().indexName()) - .append(":") - .append(terms != null ? terms.toString() : "") - .toString(); - } - - @Override - public DocIdSet getDocIdSet(LeafReaderContext context, Bits acceptDocs) throws IOException { - // make sure there are terms to filter on - if (terms == null || terms.isEmpty()) return null; - - final SortedBinaryDocValues values = fieldData.load(context).getBytesValues(); // load fielddata - return new DocValuesDocIdSet(context.reader().maxDoc(), acceptDocs) { - @Override - protected boolean matchDoc(int doc) { - values.setDocument(doc); - final int numVals = values.count(); - for (int i = 0; i < numVals; i++) { - if (terms.contains(values.valueAt(i))) { - return true; - } - } - - return false; - } - - @Override - public long ramBytesUsed() { - return 0; - } - }; - } - } - - /** - * Filters on non-floating point numeric fields. - */ - protected static class LongsFieldDataFilter extends FieldDataTermsFilter { - - final LongOpenHashSet terms; - - protected LongsFieldDataFilter(IndexNumericFieldData fieldData, LongOpenHashSet terms) { - super(fieldData); - this.terms = terms; - } - - @Override - public boolean equals(Object obj) { - if (super.equals(obj) == false) { - return false; - } - return Objects.equals(terms, ((BytesFieldDataFilter) obj).terms); - } - - @Override - public int hashCode() { - return 31 * super.hashCode() + Objects.hashCode(terms); - } - - @Override - public String toString(String field) { - final StringBuilder sb = new StringBuilder("LongsFieldDataFilter:"); - return sb - .append(fieldData.getFieldNames().indexName()) - .append(":") - .append(terms != null ? terms.toString() : "") - .toString(); - } - - @Override - public DocIdSet getDocIdSet(LeafReaderContext context, Bits acceptDocs) throws IOException { - // make sure there are terms to filter on - if (terms == null || terms.isEmpty()) return null; - - IndexNumericFieldData numericFieldData = (IndexNumericFieldData) fieldData; - if (!numericFieldData.getNumericType().isFloatingPoint()) { - final SortedNumericDocValues values = numericFieldData.load(context).getLongValues(); // load fielddata - return new DocValuesDocIdSet(context.reader().maxDoc(), acceptDocs) { - @Override - protected boolean matchDoc(int doc) { - values.setDocument(doc); - final int numVals = values.count(); - for (int i = 0; i < numVals; i++) { - if (terms.contains(values.valueAt(i))) { - return true; - } - } - - return false; - } - }; - } - - // only get here if wrong fielddata type in which case - // no docs will match so we just return null. - return null; - } - } - - /** - * Filters on floating point numeric fields. - */ - protected static class DoublesFieldDataFilter extends FieldDataTermsFilter { - - final DoubleOpenHashSet terms; - - protected DoublesFieldDataFilter(IndexNumericFieldData fieldData, DoubleOpenHashSet terms) { - super(fieldData); - this.terms = terms; - } - - @Override - public boolean equals(Object obj) { - if (super.equals(obj) == false) { - return false; - } - return Objects.equals(terms, ((BytesFieldDataFilter) obj).terms); - } - - @Override - public int hashCode() { - return 31 * super.hashCode() + Objects.hashCode(terms); - } - - @Override - public String toString(String field) { - final StringBuilder sb = new StringBuilder("DoublesFieldDataFilter"); - return sb - .append(fieldData.getFieldNames().indexName()) - .append(":") - .append(terms != null ? terms.toString() : "") - .toString(); - } - - @Override - public DocIdSet getDocIdSet(LeafReaderContext context, Bits acceptDocs) throws IOException { - // make sure there are terms to filter on - if (terms == null || terms.isEmpty()) return null; - - // verify we have a floating point numeric fielddata - IndexNumericFieldData indexNumericFieldData = (IndexNumericFieldData) fieldData; - if (indexNumericFieldData.getNumericType().isFloatingPoint()) { - final SortedNumericDoubleValues values = indexNumericFieldData.load(context).getDoubleValues(); // load fielddata - return new DocValuesDocIdSet(context.reader().maxDoc(), acceptDocs) { - @Override - protected boolean matchDoc(int doc) { - values.setDocument(doc); - final int numVals = values.count(); - - for (int i = 0; i < numVals; i++) { - if (terms.contains(values.valueAt(i))) { - return true; - } - } - - return false; - } - }; - } - - // only get here if wrong fielddata type in which case - // no docs will match so we just return null. - return null; - } - } -} diff --git a/src/main/java/org/elasticsearch/index/search/NumericRangeFieldDataFilter.java b/src/main/java/org/elasticsearch/index/search/NumericRangeFieldDataFilter.java deleted file mode 100644 index 43b279c073b..00000000000 --- a/src/main/java/org/elasticsearch/index/search/NumericRangeFieldDataFilter.java +++ /dev/null @@ -1,363 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.search; - -import java.io.IOException; - -import org.apache.lucene.index.LeafReaderContext; -import org.apache.lucene.index.SortedNumericDocValues; -import org.apache.lucene.search.DocIdSet; -import org.apache.lucene.search.DocValuesDocIdSet; -import org.apache.lucene.search.Filter; -import org.apache.lucene.util.Bits; -import org.apache.lucene.util.NumericUtils; -import org.elasticsearch.index.fielddata.IndexNumericFieldData; -import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; - -/** - * A numeric filter that can be much faster than {@link org.apache.lucene.search.NumericRangeFilter} at the - * expense of loading numeric values of the field to memory using {@link org.elasticsearch.index.cache.field.data.FieldDataCache}. - */ -// TODO: these filters should not iterate over all values but be more selective like Lucene's DocTermOrdsRangeFilter -public abstract class NumericRangeFieldDataFilter extends Filter { - final IndexNumericFieldData indexFieldData; - final T lowerVal; - final T upperVal; - final boolean includeLower; - final boolean includeUpper; - - public String getField() { - return indexFieldData.getFieldNames().indexName(); - } - - public T getLowerVal() { - return lowerVal; - } - - public T getUpperVal() { - return upperVal; - } - - public boolean isIncludeLower() { - return includeLower; - } - - public boolean isIncludeUpper() { - return includeUpper; - } - - protected NumericRangeFieldDataFilter(IndexNumericFieldData indexFieldData, T lowerVal, T upperVal, boolean includeLower, boolean includeUpper) { - this.indexFieldData = indexFieldData; - this.lowerVal = lowerVal; - this.upperVal = upperVal; - this.includeLower = includeLower; - this.includeUpper = includeUpper; - } - - @Override - public final String toString(String field) { - final StringBuilder sb = new StringBuilder(indexFieldData.getFieldNames().indexName()).append(":"); - return sb.append(includeLower ? '[' : '{') - .append((lowerVal == null) ? "*" : lowerVal.toString()) - .append(" TO ") - .append((upperVal == null) ? "*" : upperVal.toString()) - .append(includeUpper ? ']' : '}') - .toString(); - } - - @Override - public final boolean equals(Object o) { - if (this == o) return true; - if (super.equals(o) == false) return false; - NumericRangeFieldDataFilter other = (NumericRangeFieldDataFilter) o; - - if (!this.indexFieldData.getFieldNames().indexName().equals(other.indexFieldData.getFieldNames().indexName()) - || this.includeLower != other.includeLower - || this.includeUpper != other.includeUpper - ) { - return false; - } - if (this.lowerVal != null ? !this.lowerVal.equals(other.lowerVal) : other.lowerVal != null) return false; - if (this.upperVal != null ? !this.upperVal.equals(other.upperVal) : other.upperVal != null) return false; - return true; - } - - @Override - public final int hashCode() { - int h = super.hashCode(); - h = 31 * h + indexFieldData.getFieldNames().indexName().hashCode(); - h ^= (lowerVal != null) ? lowerVal.hashCode() : 550356204; - h = (h << 1) | (h >>> 31); // rotate to distinguish lower from upper - h ^= (upperVal != null) ? upperVal.hashCode() : -1674416163; - h ^= (includeLower ? 1549299360 : -365038026) ^ (includeUpper ? 1721088258 : 1948649653); - return h; - } - - public static NumericRangeFieldDataFilter newByteRange(IndexNumericFieldData indexFieldData, Byte lowerVal, Byte upperVal, boolean includeLower, boolean includeUpper) { - return new NumericRangeFieldDataFilter(indexFieldData, lowerVal, upperVal, includeLower, includeUpper) { - @Override - public DocIdSet getDocIdSet(LeafReaderContext ctx, Bits acceptedDocs) throws IOException { - final byte inclusiveLowerPoint, inclusiveUpperPoint; - if (lowerVal != null) { - byte i = lowerVal.byteValue(); - if (!includeLower && i == Byte.MAX_VALUE) - return null; - inclusiveLowerPoint = (byte) (includeLower ? i : (i + 1)); - } else { - inclusiveLowerPoint = Byte.MIN_VALUE; - } - if (upperVal != null) { - byte i = upperVal.byteValue(); - if (!includeUpper && i == Byte.MIN_VALUE) - return null; - inclusiveUpperPoint = (byte) (includeUpper ? i : (i - 1)); - } else { - inclusiveUpperPoint = Byte.MAX_VALUE; - } - - if (inclusiveLowerPoint > inclusiveUpperPoint) - return null; - - final SortedNumericDocValues values = indexFieldData.load(ctx).getLongValues(); - return new LongRangeMatchDocIdSet(ctx.reader().maxDoc(), acceptedDocs, values, inclusiveLowerPoint, inclusiveUpperPoint); - } - }; - } - - - public static NumericRangeFieldDataFilter newShortRange(IndexNumericFieldData indexFieldData, Short lowerVal, Short upperVal, boolean includeLower, boolean includeUpper) { - return new NumericRangeFieldDataFilter(indexFieldData, lowerVal, upperVal, includeLower, includeUpper) { - @Override - public DocIdSet getDocIdSet(LeafReaderContext ctx, Bits acceptedDocs) throws IOException { - final short inclusiveLowerPoint, inclusiveUpperPoint; - if (lowerVal != null) { - short i = lowerVal.shortValue(); - if (!includeLower && i == Short.MAX_VALUE) - return null; - inclusiveLowerPoint = (short) (includeLower ? i : (i + 1)); - } else { - inclusiveLowerPoint = Short.MIN_VALUE; - } - if (upperVal != null) { - short i = upperVal.shortValue(); - if (!includeUpper && i == Short.MIN_VALUE) - return null; - inclusiveUpperPoint = (short) (includeUpper ? i : (i - 1)); - } else { - inclusiveUpperPoint = Short.MAX_VALUE; - } - - if (inclusiveLowerPoint > inclusiveUpperPoint) - return null; - - final SortedNumericDocValues values = indexFieldData.load(ctx).getLongValues(); - return new LongRangeMatchDocIdSet(ctx.reader().maxDoc(), acceptedDocs, values, inclusiveLowerPoint, inclusiveUpperPoint); - } - }; - } - - public static NumericRangeFieldDataFilter newIntRange(IndexNumericFieldData indexFieldData, Integer lowerVal, Integer upperVal, boolean includeLower, boolean includeUpper) { - return new NumericRangeFieldDataFilter(indexFieldData, lowerVal, upperVal, includeLower, includeUpper) { - @Override - public DocIdSet getDocIdSet(LeafReaderContext ctx, Bits acceptedDocs) throws IOException { - final int inclusiveLowerPoint, inclusiveUpperPoint; - if (lowerVal != null) { - int i = lowerVal.intValue(); - if (!includeLower && i == Integer.MAX_VALUE) - return null; - inclusiveLowerPoint = includeLower ? i : (i + 1); - } else { - inclusiveLowerPoint = Integer.MIN_VALUE; - } - if (upperVal != null) { - int i = upperVal.intValue(); - if (!includeUpper && i == Integer.MIN_VALUE) - return null; - inclusiveUpperPoint = includeUpper ? i : (i - 1); - } else { - inclusiveUpperPoint = Integer.MAX_VALUE; - } - - if (inclusiveLowerPoint > inclusiveUpperPoint) - return null; - - final SortedNumericDocValues values = indexFieldData.load(ctx).getLongValues(); - return new LongRangeMatchDocIdSet(ctx.reader().maxDoc(), acceptedDocs, values, inclusiveLowerPoint, inclusiveUpperPoint); - } - }; - } - - public static NumericRangeFieldDataFilter newLongRange(IndexNumericFieldData indexFieldData, Long lowerVal, Long upperVal, boolean includeLower, boolean includeUpper) { - return new NumericRangeFieldDataFilter(indexFieldData, lowerVal, upperVal, includeLower, includeUpper) { - @Override - public DocIdSet getDocIdSet(LeafReaderContext ctx, Bits acceptedDocs) throws IOException { - final long inclusiveLowerPoint, inclusiveUpperPoint; - if (lowerVal != null) { - long i = lowerVal.longValue(); - if (!includeLower && i == Long.MAX_VALUE) - return null; - inclusiveLowerPoint = includeLower ? i : (i + 1l); - } else { - inclusiveLowerPoint = Long.MIN_VALUE; - } - if (upperVal != null) { - long i = upperVal.longValue(); - if (!includeUpper && i == Long.MIN_VALUE) - return null; - inclusiveUpperPoint = includeUpper ? i : (i - 1l); - } else { - inclusiveUpperPoint = Long.MAX_VALUE; - } - - if (inclusiveLowerPoint > inclusiveUpperPoint) - return null; - - final SortedNumericDocValues values = indexFieldData.load(ctx).getLongValues(); - return new LongRangeMatchDocIdSet(ctx.reader().maxDoc(), acceptedDocs, values, inclusiveLowerPoint, inclusiveUpperPoint); - - } - }; - } - - public static NumericRangeFieldDataFilter newFloatRange(IndexNumericFieldData indexFieldData, Float lowerVal, Float upperVal, boolean includeLower, boolean includeUpper) { - return new NumericRangeFieldDataFilter(indexFieldData, lowerVal, upperVal, includeLower, includeUpper) { - @Override - public DocIdSet getDocIdSet(LeafReaderContext ctx, Bits acceptedDocs) throws IOException { - // we transform the floating point numbers to sortable integers - // using NumericUtils to easier find the next bigger/lower value - final float inclusiveLowerPoint, inclusiveUpperPoint; - if (lowerVal != null) { - float f = lowerVal.floatValue(); - if (!includeUpper && f > 0.0f && Float.isInfinite(f)) - return null; - int i = NumericUtils.floatToSortableInt(f); - inclusiveLowerPoint = NumericUtils.sortableIntToFloat(includeLower ? i : (i + 1)); - } else { - inclusiveLowerPoint = Float.NEGATIVE_INFINITY; - } - if (upperVal != null) { - float f = upperVal.floatValue(); - if (!includeUpper && f < 0.0f && Float.isInfinite(f)) - return null; - int i = NumericUtils.floatToSortableInt(f); - inclusiveUpperPoint = NumericUtils.sortableIntToFloat(includeUpper ? i : (i - 1)); - } else { - inclusiveUpperPoint = Float.POSITIVE_INFINITY; - } - - if (inclusiveLowerPoint > inclusiveUpperPoint) - return null; - - final SortedNumericDoubleValues values = indexFieldData.load(ctx).getDoubleValues(); - return new DoubleRangeMatchDocIdSet(ctx.reader().maxDoc(), acceptedDocs, values, inclusiveLowerPoint, inclusiveUpperPoint); - } - }; - } - - public static NumericRangeFieldDataFilter newDoubleRange(IndexNumericFieldData indexFieldData, Double lowerVal, Double upperVal, boolean includeLower, boolean includeUpper) { - return new NumericRangeFieldDataFilter(indexFieldData, lowerVal, upperVal, includeLower, includeUpper) { - @Override - public DocIdSet getDocIdSet(LeafReaderContext ctx, Bits acceptedDocs) throws IOException { - // we transform the floating point numbers to sortable integers - // using NumericUtils to easier find the next bigger/lower value - final double inclusiveLowerPoint, inclusiveUpperPoint; - if (lowerVal != null) { - double f = lowerVal.doubleValue(); - if (!includeUpper && f > 0.0 && Double.isInfinite(f)) - return null; - long i = NumericUtils.doubleToSortableLong(f); - inclusiveLowerPoint = NumericUtils.sortableLongToDouble(includeLower ? i : (i + 1L)); - } else { - inclusiveLowerPoint = Double.NEGATIVE_INFINITY; - } - if (upperVal != null) { - double f = upperVal.doubleValue(); - if (!includeUpper && f < 0.0 && Double.isInfinite(f)) - return null; - long i = NumericUtils.doubleToSortableLong(f); - inclusiveUpperPoint = NumericUtils.sortableLongToDouble(includeUpper ? i : (i - 1L)); - } else { - inclusiveUpperPoint = Double.POSITIVE_INFINITY; - } - - if (inclusiveLowerPoint > inclusiveUpperPoint) - return null; - - final SortedNumericDoubleValues values = indexFieldData.load(ctx).getDoubleValues(); - return new DoubleRangeMatchDocIdSet(ctx.reader().maxDoc(), acceptedDocs, values, inclusiveLowerPoint, inclusiveUpperPoint); - } - }; - } - - private static final class DoubleRangeMatchDocIdSet extends DocValuesDocIdSet { - private final SortedNumericDoubleValues values; - private final double inclusiveLowerPoint; - private final double inclusiveUpperPoint; - - protected DoubleRangeMatchDocIdSet(int maxDoc, Bits acceptDocs, final SortedNumericDoubleValues values,final double inclusiveLowerPoint, final double inclusiveUpperPoint ) { - super(maxDoc, acceptDocs); - this.inclusiveLowerPoint = inclusiveLowerPoint; - this.inclusiveUpperPoint = inclusiveUpperPoint; - this.values = values; - } - - @Override - protected boolean matchDoc(int doc) { - values.setDocument(doc); - int numValues = values.count(); - for (int i = 0; i < numValues; i++) { - double value = values.valueAt(i); - if (value >= inclusiveLowerPoint && value <= inclusiveUpperPoint) { - return true; - } - } - return false; - } - - } - - private static final class LongRangeMatchDocIdSet extends DocValuesDocIdSet { - private final SortedNumericDocValues values; - private final long inclusiveLowerPoint; - private final long inclusiveUpperPoint; - - protected LongRangeMatchDocIdSet(int maxDoc, Bits acceptDocs, final SortedNumericDocValues values,final long inclusiveLowerPoint, final long inclusiveUpperPoint ) { - super(maxDoc, acceptDocs); - this.inclusiveLowerPoint = inclusiveLowerPoint; - this.inclusiveUpperPoint = inclusiveUpperPoint; - this.values = values; - } - - @Override - protected boolean matchDoc(int doc) { - values.setDocument(doc); - int numValues = values.count(); - for (int i = 0; i < numValues; i++) { - long value = values.valueAt(i); - if (value >= inclusiveLowerPoint && value <= inclusiveUpperPoint) { - return true; - } - } - return false; - } - - } - -} diff --git a/src/main/java/org/elasticsearch/index/shard/IndexShard.java b/src/main/java/org/elasticsearch/index/shard/IndexShard.java index 2ec0dade504..d72721d9772 100644 --- a/src/main/java/org/elasticsearch/index/shard/IndexShard.java +++ b/src/main/java/org/elasticsearch/index/shard/IndexShard.java @@ -21,10 +21,9 @@ package org.elasticsearch.index.shard; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; + import org.apache.lucene.codecs.PostingsFormat; import org.apache.lucene.index.CheckIndex; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.FilteredQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.join.BitDocIdSetFilter; import org.apache.lucene.store.AlreadyClosedException; @@ -563,12 +562,12 @@ public class IndexShard extends AbstractIndexShardComponent { types = Strings.EMPTY_ARRAY; } Query query = queryParserService.parseQuery(source).query(); - Filter searchFilter = mapperService.searchFilter(types); + Query searchFilter = mapperService.searchFilter(types); if (searchFilter != null) { - query = new FilteredQuery(query, searchFilter); + query = Queries.filtered(query, searchFilter); } - Filter aliasFilter = indexAliasesService.aliasFilter(filteringAliases); + Query aliasFilter = indexAliasesService.aliasFilter(filteringAliases); BitDocIdSetFilter parentFilter = mapperService.hasNested() ? indexCache.bitsetFilterCache().getBitDocIdSetFilter(Queries.newNonNestedFilter()) : null; return new Engine.DeleteByQuery(query, source, filteringAliases, aliasFilter, parentFilter, origin, startTime, types); } diff --git a/src/main/java/org/elasticsearch/indices/query/IndicesQueriesModule.java b/src/main/java/org/elasticsearch/indices/query/IndicesQueriesModule.java index d70995ffebf..e911b25aba7 100644 --- a/src/main/java/org/elasticsearch/indices/query/IndicesQueriesModule.java +++ b/src/main/java/org/elasticsearch/indices/query/IndicesQueriesModule.java @@ -32,8 +32,6 @@ public class IndicesQueriesModule extends AbstractModule { private Set> queryParsersClasses = Sets.newHashSet(); private Set queryParsers = Sets.newHashSet(); - private Set> filterParsersClasses = Sets.newHashSet(); - private Set filterParsers = Sets.newHashSet(); public synchronized IndicesQueriesModule addQuery(Class queryParser) { queryParsersClasses.add(queryParser); @@ -45,16 +43,6 @@ public class IndicesQueriesModule extends AbstractModule { return this; } - public synchronized IndicesQueriesModule addFilter(Class filterParser) { - filterParsersClasses.add(filterParser); - return this; - } - - public synchronized IndicesQueriesModule addFilter(FilterParser filterParser) { - filterParsers.add(filterParser); - return this; - } - @Override protected void configure() { bind(IndicesQueriesRegistry.class).asEagerSingleton(); @@ -103,48 +91,25 @@ public class IndicesQueriesModule extends AbstractModule { qpBinders.addBinding().to(FunctionScoreQueryParser.class).asEagerSingleton(); qpBinders.addBinding().to(SimpleQueryStringParser.class).asEagerSingleton(); qpBinders.addBinding().to(TemplateQueryParser.class).asEagerSingleton(); + qpBinders.addBinding().to(TypeQueryParser.class).asEagerSingleton(); + qpBinders.addBinding().to(LimitQueryParser.class).asEagerSingleton(); + qpBinders.addBinding().to(TermsQueryParser.class).asEagerSingleton(); + qpBinders.addBinding().to(ScriptQueryParser.class).asEagerSingleton(); + qpBinders.addBinding().to(GeoDistanceQueryParser.class).asEagerSingleton(); + qpBinders.addBinding().to(GeoDistanceRangeQueryParser.class).asEagerSingleton(); + qpBinders.addBinding().to(GeoBoundingBoxQueryParser.class).asEagerSingleton(); + qpBinders.addBinding().to(GeohashCellQuery.Parser.class).asEagerSingleton(); + qpBinders.addBinding().to(GeoPolygonQueryParser.class).asEagerSingleton(); + qpBinders.addBinding().to(QueryFilterParser.class).asEagerSingleton(); + qpBinders.addBinding().to(FQueryFilterParser.class).asEagerSingleton(); + qpBinders.addBinding().to(AndQueryParser.class).asEagerSingleton(); + qpBinders.addBinding().to(OrQueryParser.class).asEagerSingleton(); + qpBinders.addBinding().to(NotQueryParser.class).asEagerSingleton(); + qpBinders.addBinding().to(ExistsQueryParser.class).asEagerSingleton(); + qpBinders.addBinding().to(MissingQueryParser.class).asEagerSingleton(); if (ShapesAvailability.JTS_AVAILABLE) { qpBinders.addBinding().to(GeoShapeQueryParser.class).asEagerSingleton(); } - - Multibinder fpBinders = Multibinder.newSetBinder(binder(), FilterParser.class); - for (Class filterParser : filterParsersClasses) { - fpBinders.addBinding().to(filterParser).asEagerSingleton(); - } - for (FilterParser filterParser : filterParsers) { - fpBinders.addBinding().toInstance(filterParser); - } - fpBinders.addBinding().to(HasChildFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(HasParentFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(NestedFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(TypeFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(IdsFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(LimitFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(TermFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(TermsFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(RangeFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(PrefixFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(RegexpFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(ScriptFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(GeoDistanceFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(GeoDistanceRangeFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(GeoBoundingBoxFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(GeohashCellFilter.Parser.class).asEagerSingleton(); - fpBinders.addBinding().to(GeoPolygonFilterParser.class).asEagerSingleton(); - if (ShapesAvailability.JTS_AVAILABLE) { - fpBinders.addBinding().to(GeoShapeFilterParser.class).asEagerSingleton(); - } - fpBinders.addBinding().to(QueryFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(FQueryFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(BoolFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(AndFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(OrFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(NotFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(MatchAllFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(ExistsFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(MissingFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(IndicesFilterParser.class).asEagerSingleton(); - fpBinders.addBinding().to(WrapperFilterParser.class).asEagerSingleton(); } } diff --git a/src/main/java/org/elasticsearch/indices/query/IndicesQueriesRegistry.java b/src/main/java/org/elasticsearch/indices/query/IndicesQueriesRegistry.java index dff63a93a65..a4e3116b41a 100644 --- a/src/main/java/org/elasticsearch/indices/query/IndicesQueriesRegistry.java +++ b/src/main/java/org/elasticsearch/indices/query/IndicesQueriesRegistry.java @@ -21,10 +21,10 @@ package org.elasticsearch.indices.query; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; + import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.index.query.FilterParser; import org.elasticsearch.index.query.QueryParser; import java.util.Map; @@ -36,22 +36,15 @@ import java.util.Set; public class IndicesQueriesRegistry extends AbstractComponent { private ImmutableMap queryParsers; - private ImmutableMap filterParsers; @Inject - public IndicesQueriesRegistry(Settings settings, Set injectedQueryParsers, Set injectedFilterParsers) { + public IndicesQueriesRegistry(Settings settings, Set injectedQueryParsers) { super(settings); Map queryParsers = Maps.newHashMap(); for (QueryParser queryParser : injectedQueryParsers) { addQueryParser(queryParsers, queryParser); } this.queryParsers = ImmutableMap.copyOf(queryParsers); - - Map filterParsers = Maps.newHashMap(); - for (FilterParser filterParser : injectedFilterParsers) { - addFilterParser(filterParsers, filterParser); - } - this.filterParsers = ImmutableMap.copyOf(filterParsers); } /** @@ -63,29 +56,13 @@ public class IndicesQueriesRegistry extends AbstractComponent { this.queryParsers = ImmutableMap.copyOf(queryParsers); } - public synchronized void addFilterParser(FilterParser filterParser) { - Map filterParsers = Maps.newHashMap(this.filterParsers); - addFilterParser(filterParsers, filterParser); - this.filterParsers = ImmutableMap.copyOf(filterParsers); - } - public ImmutableMap queryParsers() { return queryParsers; } - public ImmutableMap filterParsers() { - return filterParsers; - } - private void addQueryParser(Map queryParsers, QueryParser queryParser) { for (String name : queryParser.names()) { queryParsers.put(name, queryParser); } } - - private void addFilterParser(Map filterParsers, FilterParser filterParser) { - for (String name : filterParser.names()) { - filterParsers.put(name, filterParser); - } - } } \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/percolator/PercolateContext.java b/src/main/java/org/elasticsearch/percolator/PercolateContext.java index d752052e829..592423f63f6 100644 --- a/src/main/java/org/elasticsearch/percolator/PercolateContext.java +++ b/src/main/java/org/elasticsearch/percolator/PercolateContext.java @@ -23,7 +23,10 @@ import com.google.common.collect.ImmutableList; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.LeafReaderContext; -import org.apache.lucene.search.*; +import org.apache.lucene.search.IndexSearcher; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.ScoreDoc; +import org.apache.lucene.search.Sort; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.Counter; import org.elasticsearch.action.percolate.PercolateShardRequest; @@ -35,7 +38,6 @@ import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.analysis.AnalysisService; import org.elasticsearch.index.cache.bitset.BitsetFilterCache; -import org.elasticsearch.index.cache.filter.FilterCache; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.fielddata.IndexFieldDataService; import org.elasticsearch.index.mapper.FieldMapper; @@ -43,7 +45,6 @@ import org.elasticsearch.index.mapper.FieldMappers; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.ParsedDocument; import org.elasticsearch.index.query.IndexQueryParserService; -import org.elasticsearch.index.query.ParsedFilter; import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.similarity.SimilarityService; @@ -60,7 +61,11 @@ import org.elasticsearch.search.fetch.innerhits.InnerHitsContext; import org.elasticsearch.search.fetch.script.ScriptFieldsContext; import org.elasticsearch.search.fetch.source.FetchSourceContext; import org.elasticsearch.search.highlight.SearchContextHighlight; -import org.elasticsearch.search.internal.*; +import org.elasticsearch.search.internal.ContextIndexSearcher; +import org.elasticsearch.search.internal.InternalSearchHit; +import org.elasticsearch.search.internal.InternalSearchHitField; +import org.elasticsearch.search.internal.SearchContext; +import org.elasticsearch.search.internal.ShardSearchRequest; import org.elasticsearch.search.lookup.LeafSearchLookup; import org.elasticsearch.search.lookup.SearchLookup; import org.elasticsearch.search.query.QuerySearchResult; @@ -92,7 +97,7 @@ public class PercolateContext extends SearchContext { private final ScriptService scriptService; private final ConcurrentMap percolateQueries; private final int numberOfShards; - private final Filter aliasFilter; + private final Query aliasFilter; private String[] types; private Engine.Searcher docSearcher; @@ -112,7 +117,7 @@ public class PercolateContext extends SearchContext { public PercolateContext(PercolateShardRequest request, SearchShardTarget searchShardTarget, IndexShard indexShard, IndexService indexService, PageCacheRecycler pageCacheRecycler, - BigArrays bigArrays, ScriptService scriptService, Filter aliasFilter) { + BigArrays bigArrays, ScriptService scriptService, Query aliasFilter) { this.indexShard = indexShard; this.indexService = indexService; this.fieldDataService = indexService.fieldData(); @@ -148,7 +153,7 @@ public class PercolateContext extends SearchContext { } hitContext().reset( new InternalSearchHit(0, "unknown", new StringText(parsedDocument.type()), fields), - atomicReaderContext, 0, indexReader + atomicReaderContext, 0, docSearcher.searcher() ); } @@ -280,7 +285,7 @@ public class PercolateContext extends SearchContext { } @Override - public Filter searchFilter(String[] types) { + public Query searchFilter(String[] types) { return aliasFilter(); } @@ -497,17 +502,17 @@ public class PercolateContext extends SearchContext { } @Override - public SearchContext parsedPostFilter(ParsedFilter postFilter) { + public SearchContext parsedPostFilter(ParsedQuery postFilter) { throw new UnsupportedOperationException(); } @Override - public ParsedFilter parsedPostFilter() { + public ParsedQuery parsedPostFilter() { return null; } @Override - public Filter aliasFilter() { + public Query aliasFilter() { return aliasFilter; } diff --git a/src/main/java/org/elasticsearch/percolator/PercolatorService.java b/src/main/java/org/elasticsearch/percolator/PercolatorService.java index 1284edc4902..6bf8c1278b8 100644 --- a/src/main/java/org/elasticsearch/percolator/PercolatorService.java +++ b/src/main/java/org/elasticsearch/percolator/PercolatorService.java @@ -28,16 +28,12 @@ import org.apache.lucene.index.memory.MemoryIndex; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.ConstantScoreQuery; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.FilteredQuery; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Query; -import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.CloseableThreadLocal; -import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.action.percolate.PercolateResponse; import org.elasticsearch.action.percolate.PercolateShardRequest; @@ -185,7 +181,7 @@ public class PercolatorService extends AbstractComponent { indexShard.shardId().index().name(), request.indices() ); - Filter aliasFilter = percolateIndexService.aliasesService().aliasFilter(filteringAliases); + Query aliasFilter = percolateIndexService.aliasesService().aliasFilter(filteringAliases); SearchShardTarget searchShardTarget = new SearchShardTarget(clusterService.localNode().id(), request.shardId().getIndex(), request.shardId().id()); final PercolateContext context = new PercolateContext( @@ -311,7 +307,7 @@ public class PercolatorService extends AbstractComponent { if (context.percolateQuery() != null) { throw new ElasticsearchParseException("Either specify query or filter, not both"); } - Filter filter = documentIndexService.queryParserService().parseInnerFilter(parser).filter(); + Query filter = documentIndexService.queryParserService().parseInnerFilter(parser).query(); context.percolateQuery(new ConstantScoreQuery(filter)); } else if ("sort".equals(currentFieldName)) { parseSort(parser, context); @@ -794,19 +790,19 @@ public class PercolatorService extends AbstractComponent { }; private void queryBasedPercolating(Engine.Searcher percolatorSearcher, PercolateContext context, QueryCollector percolateCollector) throws IOException { - Filter percolatorTypeFilter = context.indexService().mapperService().documentMapper(TYPE_NAME).typeFilter(); + Query percolatorTypeFilter = context.indexService().mapperService().documentMapper(TYPE_NAME).typeFilter(); - final Filter filter; + final Query filter; if (context.aliasFilter() != null) { BooleanQuery booleanFilter = new BooleanQuery(); booleanFilter.add(context.aliasFilter(), BooleanClause.Occur.MUST); booleanFilter.add(percolatorTypeFilter, BooleanClause.Occur.MUST); - filter = new QueryWrapperFilter(booleanFilter); + filter = booleanFilter; } else { filter = percolatorTypeFilter; } - FilteredQuery query = new FilteredQuery(context.percolateQuery(), filter); + Query query = Queries.filtered(context.percolateQuery(), filter); percolatorSearcher.searcher().search(query, percolateCollector); percolateCollector.aggregatorCollector.postCollection(); if (context.aggregations() != null) { diff --git a/src/main/java/org/elasticsearch/search/aggregations/bucket/children/ChildrenParser.java b/src/main/java/org/elasticsearch/search/aggregations/bucket/children/ChildrenParser.java index 2f50bbf69ee..c3a427c1b48 100644 --- a/src/main/java/org/elasticsearch/search/aggregations/bucket/children/ChildrenParser.java +++ b/src/main/java/org/elasticsearch/search/aggregations/bucket/children/ChildrenParser.java @@ -19,6 +19,7 @@ package org.elasticsearch.search.aggregations.bucket.children; import org.apache.lucene.search.Filter; +import org.apache.lucene.search.QueryWrapperFilter; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.fielddata.plain.ParentChildIndexFieldData; import org.elasticsearch.index.mapper.DocumentMapper; @@ -84,8 +85,9 @@ public class ChildrenParser implements Aggregator.Parser { parentType = parentFieldMapper.type(); DocumentMapper parentDocMapper = context.mapperService().documentMapper(parentType); if (parentDocMapper != null) { - parentFilter = parentDocMapper.typeFilter(); - childFilter = childDocMapper.typeFilter(); + // TODO: use the query API + parentFilter = new QueryWrapperFilter(parentDocMapper.typeFilter()); + childFilter = new QueryWrapperFilter(childDocMapper.typeFilter()); ParentChildIndexFieldData parentChildIndexFieldData = context.fieldData().getForField(parentFieldMapper); config.fieldContext(new FieldContext(parentFieldMapper.names().indexName(), parentChildIndexFieldData, parentFieldMapper)); } else { diff --git a/src/main/java/org/elasticsearch/search/aggregations/bucket/filter/FilterAggregationBuilder.java b/src/main/java/org/elasticsearch/search/aggregations/bucket/filter/FilterAggregationBuilder.java index 808281ea6e9..45d40bd34ba 100644 --- a/src/main/java/org/elasticsearch/search/aggregations/bucket/filter/FilterAggregationBuilder.java +++ b/src/main/java/org/elasticsearch/search/aggregations/bucket/filter/FilterAggregationBuilder.java @@ -20,7 +20,7 @@ package org.elasticsearch.search.aggregations.bucket.filter; import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.FilterBuilder; +import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.builder.SearchSourceBuilderException; @@ -31,7 +31,7 @@ import java.io.IOException; */ public class FilterAggregationBuilder extends AggregationBuilder { - private FilterBuilder filter; + private QueryBuilder filter; /** * Sole constructor. @@ -44,7 +44,7 @@ public class FilterAggregationBuilder extends AggregationBuilder { - private Map keyedFilters = null; - private List nonKeyedFilters = null; + private Map keyedFilters = null; + private List nonKeyedFilters = null; /** * Sole constructor. @@ -50,7 +50,7 @@ public class FiltersAggregationBuilder extends AggregationBuilder(); } @@ -62,7 +62,7 @@ public class FiltersAggregationBuilder extends AggregationBuilder(); } @@ -83,7 +83,7 @@ public class FiltersAggregationBuilder extends AggregationBuilder entry : keyedFilters.entrySet()) { + for (Map.Entry entry : keyedFilters.entrySet()) { builder.field(entry.getKey()); entry.getValue().toXContent(builder, params); } @@ -91,7 +91,7 @@ public class FiltersAggregationBuilder extends AggregationBuilder cache; - public void reset(InternalSearchHit hit, LeafReaderContext context, int docId, IndexReader topLevelReader) { + public void reset(InternalSearchHit hit, LeafReaderContext context, int docId, IndexSearcher searcher) { this.hit = hit; this.readerContext = context; this.docId = docId; - this.topLevelReader = topLevelReader; + this.searcher = searcher; } public InternalSearchHit hit() { @@ -65,7 +67,11 @@ public interface FetchSubPhase { } public IndexReader topLevelReader() { - return topLevelReader; + return searcher.getIndexReader(); + } + + public IndexSearcher topLevelSearcher() { + return searcher; } public Map cache() { diff --git a/src/main/java/org/elasticsearch/search/fetch/innerhits/InnerHitsContext.java b/src/main/java/org/elasticsearch/search/fetch/innerhits/InnerHitsContext.java index 8f0e2a1799c..13b08dd49ad 100644 --- a/src/main/java/org/elasticsearch/search/fetch/innerhits/InnerHitsContext.java +++ b/src/main/java/org/elasticsearch/search/fetch/innerhits/InnerHitsContext.java @@ -98,7 +98,7 @@ public final class InnerHitsContext { @Override public ParsedQuery parsedQuery() { - return new ParsedQuery(query, ImmutableMap.of()); + return new ParsedQuery(query, ImmutableMap.of()); } public abstract TopDocs topDocs(SearchContext context, FetchSubPhase.HitContext hitContext) throws IOException; @@ -307,7 +307,7 @@ public final class InnerHitsContext { } } Filter filter = new QueryWrapperFilter(new TermQuery(new Term(field, term))); // Only include docs that have the current hit as parent - Filter typeFilter = documentMapper.typeFilter(); // Only include docs that have this inner hits type. + Query typeFilter = documentMapper.typeFilter(); // Only include docs that have this inner hits type. BooleanQuery filteredQuery = new BooleanQuery(); filteredQuery.add(query, Occur.MUST); diff --git a/src/main/java/org/elasticsearch/search/fetch/matchedqueries/MatchedQueriesFetchSubPhase.java b/src/main/java/org/elasticsearch/search/fetch/matchedqueries/MatchedQueriesFetchSubPhase.java index 50ed21776ba..ac4dfa5f7e3 100644 --- a/src/main/java/org/elasticsearch/search/fetch/matchedqueries/MatchedQueriesFetchSubPhase.java +++ b/src/main/java/org/elasticsearch/search/fetch/matchedqueries/MatchedQueriesFetchSubPhase.java @@ -20,14 +20,12 @@ package org.elasticsearch.search.fetch.matchedqueries; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; -import org.apache.lucene.search.DocIdSet; -import org.apache.lucene.search.DocIdSetIterator; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.TermQuery; -import org.apache.lucene.util.Bits; -import org.elasticsearch.ElasticsearchException; + +import org.apache.lucene.search.Query; +import org.apache.lucene.search.Scorer; +import org.apache.lucene.search.TwoPhaseIterator; +import org.apache.lucene.search.Weight; import org.elasticsearch.ExceptionsHelper; -import org.elasticsearch.common.lucene.docset.DocIdSets; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.internal.InternalSearchHit; @@ -82,25 +80,24 @@ public class MatchedQueriesFetchSubPhase implements FetchSubPhase { hitContext.hit().matchedQueries(matchedQueries.toArray(new String[matchedQueries.size()])); } - private void addMatchedQueries(HitContext hitContext, ImmutableMap namedFiltersAndQueries, List matchedQueries) throws IOException { - for (Map.Entry entry : namedFiltersAndQueries.entrySet()) { + private void addMatchedQueries(HitContext hitContext, ImmutableMap namedQueries, List matchedQueries) throws IOException { + for (Map.Entry entry : namedQueries.entrySet()) { String name = entry.getKey(); - Filter filter = entry.getValue(); + Query filter = entry.getValue(); - DocIdSet filterDocIdSet = filter.getDocIdSet(hitContext.readerContext(), null); // null is fine, since we filter by hitContext.docId() - if (!DocIdSets.isEmpty(filterDocIdSet)) { - Bits bits = filterDocIdSet.bits(); - if (bits != null) { - if (bits.get(hitContext.docId())) { - matchedQueries.add(name); - } - } else { - DocIdSetIterator iterator = filterDocIdSet.iterator(); - if (iterator != null) { - if (iterator.advance(hitContext.docId()) == hitContext.docId()) { - matchedQueries.add(name); - } - } + final Weight weight = hitContext.topLevelSearcher().createNormalizedWeight(filter, false); + final Scorer scorer = weight.scorer(hitContext.readerContext(), null); + if (scorer == null) { + continue; + } + final TwoPhaseIterator twoPhase = scorer.asTwoPhaseIterator(); + if (twoPhase == null) { + if (scorer.advance(hitContext.docId()) == hitContext.docId()) { + matchedQueries.add(name); + } + } else { + if (twoPhase.approximation().advance(hitContext.docId()) == hitContext.docId() && twoPhase.matches()) { + matchedQueries.add(name); } } } diff --git a/src/main/java/org/elasticsearch/search/internal/ContextIndexSearcher.java b/src/main/java/org/elasticsearch/search/internal/ContextIndexSearcher.java index 482e3ef9153..388ed8e8ae9 100644 --- a/src/main/java/org/elasticsearch/search/internal/ContextIndexSearcher.java +++ b/src/main/java/org/elasticsearch/search/internal/ContextIndexSearcher.java @@ -152,7 +152,7 @@ public class ContextIndexSearcher extends IndexSearcher implements Releasable { // this will only get applied to the actual search collector and not // to any scoped collectors, also, it will only be applied to the main collector // since that is where the filter should only work - final Weight filterWeight = createNormalizedWeight(searchContext.parsedPostFilter().filter(), false); + final Weight filterWeight = createNormalizedWeight(searchContext.parsedPostFilter().query(), false); collector = new FilteredCollector(collector, filterWeight); } if (queryCollectors != null && !queryCollectors.isEmpty()) { diff --git a/src/main/java/org/elasticsearch/search/internal/DefaultSearchContext.java b/src/main/java/org/elasticsearch/search/internal/DefaultSearchContext.java index cd50594dc0e..001219d5129 100644 --- a/src/main/java/org/elasticsearch/search/internal/DefaultSearchContext.java +++ b/src/main/java/org/elasticsearch/search/internal/DefaultSearchContext.java @@ -31,7 +31,6 @@ import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.util.Counter; -import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.cache.recycler.PageCacheRecycler; import org.elasticsearch.common.Nullable; @@ -49,7 +48,6 @@ import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.FieldMappers; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.query.IndexQueryParserService; -import org.elasticsearch.index.query.ParsedFilter; import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.similarity.SimilarityService; @@ -148,9 +146,9 @@ public class DefaultSearchContext extends SearchContext { private Query query; - private ParsedFilter postFilter; + private ParsedQuery postFilter; - private Filter aliasFilter; + private Query aliasFilter; private int[] docIdsToLoad; @@ -250,7 +248,7 @@ public class DefaultSearchContext extends SearchContext { @Override public Filter searchFilter(String[] types) { - Filter filter = mapperService().searchFilter(types); + Query filter = mapperService().searchFilter(types); if (filter == null && aliasFilter == null) { return null; } @@ -545,18 +543,18 @@ public class DefaultSearchContext extends SearchContext { } @Override - public SearchContext parsedPostFilter(ParsedFilter postFilter) { + public SearchContext parsedPostFilter(ParsedQuery postFilter) { this.postFilter = postFilter; return this; } @Override - public ParsedFilter parsedPostFilter() { + public ParsedQuery parsedPostFilter() { return this.postFilter; } @Override - public Filter aliasFilter() { + public Query aliasFilter() { return aliasFilter; } diff --git a/src/main/java/org/elasticsearch/search/internal/FilteredSearchContext.java b/src/main/java/org/elasticsearch/search/internal/FilteredSearchContext.java index 7fe5373b5e5..7fce6e96e24 100644 --- a/src/main/java/org/elasticsearch/search/internal/FilteredSearchContext.java +++ b/src/main/java/org/elasticsearch/search/internal/FilteredSearchContext.java @@ -34,7 +34,7 @@ import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.FieldMappers; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.query.IndexQueryParserService; -import org.elasticsearch.index.query.ParsedFilter; +import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.similarity.SimilarityService; @@ -348,12 +348,12 @@ public abstract class FilteredSearchContext extends SearchContext { } @Override - public SearchContext parsedPostFilter(ParsedFilter postFilter) { + public SearchContext parsedPostFilter(ParsedQuery postFilter) { return in.parsedPostFilter(postFilter); } @Override - public ParsedFilter parsedPostFilter() { + public ParsedQuery parsedPostFilter() { return in.parsedPostFilter(); } diff --git a/src/main/java/org/elasticsearch/search/internal/SearchContext.java b/src/main/java/org/elasticsearch/search/internal/SearchContext.java index 1ae74abaaf9..c60655b27ed 100644 --- a/src/main/java/org/elasticsearch/search/internal/SearchContext.java +++ b/src/main/java/org/elasticsearch/search/internal/SearchContext.java @@ -39,7 +39,6 @@ import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.FieldMappers; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.query.IndexQueryParserService; -import org.elasticsearch.index.query.ParsedFilter; import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.shard.IndexShard; @@ -235,9 +234,9 @@ public abstract class SearchContext implements Releasable { public abstract boolean trackScores(); - public abstract SearchContext parsedPostFilter(ParsedFilter postFilter); + public abstract SearchContext parsedPostFilter(ParsedQuery postFilter); - public abstract ParsedFilter parsedPostFilter(); + public abstract ParsedQuery parsedPostFilter(); public abstract Query aliasFilter(); diff --git a/src/main/java/org/elasticsearch/search/internal/SubSearchContext.java b/src/main/java/org/elasticsearch/search/internal/SubSearchContext.java index ef7909f6560..f1162a98e86 100644 --- a/src/main/java/org/elasticsearch/search/internal/SubSearchContext.java +++ b/src/main/java/org/elasticsearch/search/internal/SubSearchContext.java @@ -26,7 +26,7 @@ import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.util.Counter; import org.elasticsearch.action.search.SearchType; -import org.elasticsearch.index.query.ParsedFilter; +import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.search.Scroll; import org.elasticsearch.search.aggregations.SearchContextAggregations; import org.elasticsearch.search.fetch.FetchSearchResult; @@ -217,7 +217,7 @@ public class SubSearchContext extends FilteredSearchContext { } @Override - public SearchContext parsedPostFilter(ParsedFilter postFilter) { + public SearchContext parsedPostFilter(ParsedQuery postFilter) { throw new UnsupportedOperationException("Not supported"); } diff --git a/src/main/java/org/elasticsearch/search/query/FilterBinaryParseElement.java b/src/main/java/org/elasticsearch/search/query/FilterBinaryParseElement.java index ed9ef4117f1..facb17e61f0 100644 --- a/src/main/java/org/elasticsearch/search/query/FilterBinaryParseElement.java +++ b/src/main/java/org/elasticsearch/search/query/FilterBinaryParseElement.java @@ -20,7 +20,7 @@ package org.elasticsearch.search.query; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.query.ParsedFilter; +import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.internal.SearchContext; @@ -33,7 +33,7 @@ public class FilterBinaryParseElement implements SearchParseElement { public void parse(XContentParser parser, SearchContext context) throws Exception { byte[] filterSource = parser.binaryValue(); try (XContentParser fSourceParser = XContentFactory.xContent(filterSource).createParser(filterSource)) { - ParsedFilter filter = context.queryParserService().parseInnerFilter(fSourceParser); + ParsedQuery filter = context.queryParserService().parseInnerFilter(fSourceParser); if (filter != null) { context.parsedPostFilter(filter); } diff --git a/src/main/java/org/elasticsearch/search/query/PostFilterParseElement.java b/src/main/java/org/elasticsearch/search/query/PostFilterParseElement.java index dcd30a76d9b..bbe6b0a55df 100644 --- a/src/main/java/org/elasticsearch/search/query/PostFilterParseElement.java +++ b/src/main/java/org/elasticsearch/search/query/PostFilterParseElement.java @@ -19,7 +19,7 @@ package org.elasticsearch.search.query; import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.query.ParsedFilter; +import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.internal.SearchContext; @@ -30,7 +30,7 @@ public class PostFilterParseElement implements SearchParseElement { @Override public void parse(XContentParser parser, SearchContext context) throws Exception { - ParsedFilter postFilter = context.queryParserService().parseInnerFilter(parser); + ParsedQuery postFilter = context.queryParserService().parseInnerFilter(parser); if (postFilter != null) { context.parsedPostFilter(postFilter); } diff --git a/src/main/java/org/elasticsearch/search/sort/FieldSortBuilder.java b/src/main/java/org/elasticsearch/search/sort/FieldSortBuilder.java index 9e3f86dcf72..1a95c96d54a 100644 --- a/src/main/java/org/elasticsearch/search/sort/FieldSortBuilder.java +++ b/src/main/java/org/elasticsearch/search/sort/FieldSortBuilder.java @@ -20,7 +20,7 @@ package org.elasticsearch.search.sort; import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.FilterBuilder; +import org.elasticsearch.index.query.QueryBuilder; import java.io.IOException; @@ -41,7 +41,7 @@ public class FieldSortBuilder extends SortBuilder { private String sortMode; - private FilterBuilder nestedFilter; + private QueryBuilder nestedFilter; private String nestedPath; @@ -114,7 +114,7 @@ public class FieldSortBuilder extends SortBuilder { * Sets the nested filter that the nested objects should match with in order to be taken into account * for sorting. */ - public FieldSortBuilder setNestedFilter(FilterBuilder nestedFilter) { + public FieldSortBuilder setNestedFilter(QueryBuilder nestedFilter) { this.nestedFilter = nestedFilter; return this; } diff --git a/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortBuilder.java b/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortBuilder.java index f42cabf84bf..5a128f44e02 100644 --- a/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortBuilder.java +++ b/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortBuilder.java @@ -24,7 +24,7 @@ import org.elasticsearch.common.geo.GeoDistance; import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.FilterBuilder; +import org.elasticsearch.index.query.QueryBuilder; import java.io.IOException; import java.util.ArrayList; @@ -45,7 +45,7 @@ public class GeoDistanceSortBuilder extends SortBuilder { private DistanceUnit unit; private SortOrder order; private String sortMode; - private FilterBuilder nestedFilter; + private QueryBuilder nestedFilter; private String nestedPath; /** @@ -132,7 +132,7 @@ public class GeoDistanceSortBuilder extends SortBuilder { * Sets the nested filter that the nested objects should match with in order to be taken into account * for sorting. */ - public GeoDistanceSortBuilder setNestedFilter(FilterBuilder nestedFilter) { + public GeoDistanceSortBuilder setNestedFilter(QueryBuilder nestedFilter) { this.nestedFilter = nestedFilter; return this; } diff --git a/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortParser.java b/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortParser.java index ae16834f7af..3c4bbfe1010 100644 --- a/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortParser.java +++ b/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortParser.java @@ -24,6 +24,7 @@ import org.apache.lucene.index.NumericDocValues; import org.apache.lucene.search.DocIdSet; import org.apache.lucene.search.FieldComparator; import org.apache.lucene.search.Filter; +import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.SortField; import org.apache.lucene.search.join.BitDocIdSetFilter; import org.apache.lucene.util.BitSet; @@ -166,7 +167,8 @@ public class GeoDistanceSortParser implements SortParser { BitDocIdSetFilter rootDocumentsFilter = context.bitsetFilterCache().getBitDocIdSetFilter(Queries.newNonNestedFilter()); Filter innerDocumentsFilter; if (nestedHelper.filterFound()) { - innerDocumentsFilter = nestedHelper.getInnerFilter(); + // TODO: use queries instead + innerDocumentsFilter = new QueryWrapperFilter(nestedHelper.getInnerFilter()); } else { innerDocumentsFilter = nestedHelper.getNestedObjectMapper().nestedTypeFilter(); } diff --git a/src/main/java/org/elasticsearch/search/sort/ScriptSortBuilder.java b/src/main/java/org/elasticsearch/search/sort/ScriptSortBuilder.java index 9798f94c286..f228279b672 100644 --- a/src/main/java/org/elasticsearch/search/sort/ScriptSortBuilder.java +++ b/src/main/java/org/elasticsearch/search/sort/ScriptSortBuilder.java @@ -21,7 +21,7 @@ package org.elasticsearch.search.sort; import com.google.common.collect.Maps; import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.FilterBuilder; +import org.elasticsearch.index.query.QueryBuilder; import java.io.IOException; import java.util.Map; @@ -43,7 +43,7 @@ public class ScriptSortBuilder extends SortBuilder { private String sortMode; - private FilterBuilder nestedFilter; + private QueryBuilder nestedFilter; private String nestedPath; @@ -120,7 +120,7 @@ public class ScriptSortBuilder extends SortBuilder { * Sets the nested filter that the nested objects should match with in order to be taken into account * for sorting. */ - public ScriptSortBuilder setNestedFilter(FilterBuilder nestedFilter) { + public ScriptSortBuilder setNestedFilter(QueryBuilder nestedFilter) { this.nestedFilter = nestedFilter; return this; } diff --git a/src/main/java/org/elasticsearch/search/sort/ScriptSortParser.java b/src/main/java/org/elasticsearch/search/sort/ScriptSortParser.java index 651e5ab3a8f..bd852d418e8 100644 --- a/src/main/java/org/elasticsearch/search/sort/ScriptSortParser.java +++ b/src/main/java/org/elasticsearch/search/sort/ScriptSortParser.java @@ -22,6 +22,7 @@ package org.elasticsearch.search.sort; import org.apache.lucene.index.BinaryDocValues; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.search.Filter; +import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.SortField; import org.apache.lucene.search.join.BitDocIdSetFilter; @@ -139,7 +140,8 @@ public class ScriptSortParser implements SortParser { BitDocIdSetFilter rootDocumentsFilter = context.bitsetFilterCache().getBitDocIdSetFilter(Queries.newNonNestedFilter()); Filter innerDocumentsFilter; if (nestedHelper.filterFound()) { - innerDocumentsFilter = nestedHelper.getInnerFilter(); + // TODO: use queries instead + innerDocumentsFilter = new QueryWrapperFilter(nestedHelper.getInnerFilter()); } else { innerDocumentsFilter = nestedHelper.getNestedObjectMapper().nestedTypeFilter(); } diff --git a/src/main/java/org/elasticsearch/search/sort/SortParseElement.java b/src/main/java/org/elasticsearch/search/sort/SortParseElement.java index 3dcaf5a4896..958f5fd5802 100644 --- a/src/main/java/org/elasticsearch/search/sort/SortParseElement.java +++ b/src/main/java/org/elasticsearch/search/sort/SortParseElement.java @@ -23,6 +23,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.apache.lucene.search.Filter; +import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.join.BitDocIdSetFilter; @@ -255,7 +256,8 @@ public class SortParseElement implements SearchParseElement { BitDocIdSetFilter rootDocumentsFilter = context.bitsetFilterCache().getBitDocIdSetFilter(Queries.newNonNestedFilter()); Filter innerDocumentsFilter; if (nestedHelper.filterFound()) { - innerDocumentsFilter = nestedHelper.getInnerFilter(); + // TODO: use queries instead + innerDocumentsFilter = new QueryWrapperFilter(nestedHelper.getInnerFilter()); } else { innerDocumentsFilter = nestedHelper.getNestedObjectMapper().nestedTypeFilter(); } diff --git a/src/main/java/org/elasticsearch/search/suggest/phrase/PhraseSuggester.java b/src/main/java/org/elasticsearch/search/suggest/phrase/PhraseSuggester.java index 96fd23a56f1..70f1df4d49e 100644 --- a/src/main/java/org/elasticsearch/search/suggest/phrase/PhraseSuggester.java +++ b/src/main/java/org/elasticsearch/search/suggest/phrase/PhraseSuggester.java @@ -34,7 +34,7 @@ import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.text.StringText; import org.elasticsearch.common.text.Text; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.script.CompiledScript; import org.elasticsearch.script.ExecutableScript; @@ -168,7 +168,7 @@ public final class PhraseSuggester extends Suggester { if (isFilter) { req = client.prepareSearch() .setPreference(suggestions.getPreference()) - .setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.bytesFilter(querySource))) + .setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.bytesQuery(querySource))) .setSize(0) .setTerminateAfter(1); } else { diff --git a/src/test/java/org/elasticsearch/action/admin/HotThreadsTest.java b/src/test/java/org/elasticsearch/action/admin/HotThreadsTest.java index afada410b1d..2c27101c5d2 100644 --- a/src/test/java/org/elasticsearch/action/admin/HotThreadsTest.java +++ b/src/test/java/org/elasticsearch/action/admin/HotThreadsTest.java @@ -32,10 +32,9 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicBoolean; -import static org.elasticsearch.index.query.FilterBuilders.andFilter; -import static org.elasticsearch.index.query.FilterBuilders.notFilter; -import static org.elasticsearch.index.query.FilterBuilders.queryFilter; +import static org.elasticsearch.index.query.QueryBuilders.andQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; +import static org.elasticsearch.index.query.QueryBuilders.notQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; import static org.hamcrest.CoreMatchers.equalTo; @@ -125,10 +124,10 @@ public class HotThreadsTest extends ElasticsearchIntegrationTest { client().prepareSearch() .setQuery(matchAllQuery()) .setPostFilter( - andFilter( - queryFilter(matchAllQuery()), - notFilter(andFilter(queryFilter(termQuery("field1", "value1")), - queryFilter(termQuery("field1", "value2")))))).get(), + andQuery( + matchAllQuery(), + notQuery(andQuery(termQuery("field1", "value1"), + termQuery("field1", "value2"))))).get(), 3l); } latch.await(); diff --git a/src/test/java/org/elasticsearch/aliases/IndexAliasesTests.java b/src/test/java/org/elasticsearch/aliases/IndexAliasesTests.java index 1e533ef5333..b033fa812cc 100644 --- a/src/test/java/org/elasticsearch/aliases/IndexAliasesTests.java +++ b/src/test/java/org/elasticsearch/aliases/IndexAliasesTests.java @@ -34,8 +34,7 @@ import org.elasticsearch.cluster.metadata.AliasMetaData; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.StopWatch; import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.index.query.FilterBuilder; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.rest.action.admin.indices.alias.delete.AliasesMissingException; @@ -57,14 +56,30 @@ import java.util.concurrent.TimeUnit; import static com.google.common.collect.Sets.newHashSet; import static org.elasticsearch.client.Requests.createIndexRequest; import static org.elasticsearch.client.Requests.indexRequest; -import static org.elasticsearch.cluster.metadata.IndexMetaData.*; +import static org.elasticsearch.cluster.metadata.IndexMetaData.INDEX_METADATA_BLOCK; +import static org.elasticsearch.cluster.metadata.IndexMetaData.INDEX_READ_ONLY_BLOCK; +import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_BLOCKS_METADATA; +import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_BLOCKS_READ; +import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_BLOCKS_WRITE; +import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_READ_ONLY; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; -import static org.elasticsearch.index.query.FilterBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.hasChildQuery; +import static org.elasticsearch.index.query.QueryBuilders.hasParentQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.test.hamcrest.CollectionAssertions.hasKey; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; -import static org.hamcrest.Matchers.*; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBlocked; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @@ -133,7 +148,7 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { ensureGreen(); logger.info("--> aliasing index [test] with [alias1] and filter [user:kimchy]"); - FilterBuilder filter = termFilter("user", "kimchy"); + QueryBuilder filter = termQuery("user", "kimchy"); assertAcked(admin().indices().prepareAliases().addAlias("test", "alias1", filter)); // For now just making sure that filter was stored with the alias @@ -164,9 +179,9 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { logger.info("--> adding filtering aliases to index [test]"); assertAcked(admin().indices().prepareAliases().addAlias("test", "alias1")); assertAcked(admin().indices().prepareAliases().addAlias("test", "alias2")); - assertAcked(admin().indices().prepareAliases().addAlias("test", "foos", termFilter("name", "foo"))); - assertAcked(admin().indices().prepareAliases().addAlias("test", "bars", termFilter("name", "bar"))); - assertAcked(admin().indices().prepareAliases().addAlias("test", "tests", termFilter("name", "test"))); + assertAcked(admin().indices().prepareAliases().addAlias("test", "foos", termQuery("name", "foo"))); + assertAcked(admin().indices().prepareAliases().addAlias("test", "bars", termQuery("name", "bar"))); + assertAcked(admin().indices().prepareAliases().addAlias("test", "tests", termQuery("name", "test"))); logger.info("--> indexing against [test]"); client().index(indexRequest("test").type("type1").id("1").source(source("1", "foo test")).refresh(true)).actionGet(); @@ -195,7 +210,7 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { .get(); assertSearchResponse(searchResponse); Global global = searchResponse.getAggregations().get("global"); - Terms terms = global.getAggregations().get("test");System.out.println(searchResponse); + Terms terms = global.getAggregations().get("test"); assertThat(terms.getBuckets().size(), equalTo(4)); logger.info("--> checking single filtering alias search with global facets and sort"); @@ -246,13 +261,13 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { logger.info("--> adding filtering aliases to index [test1]"); assertAcked(admin().indices().prepareAliases().addAlias("test1", "aliasToTest1")); assertAcked(admin().indices().prepareAliases().addAlias("test1", "aliasToTests")); - assertAcked(admin().indices().prepareAliases().addAlias("test1", "foos", termFilter("name", "foo"))); - assertAcked(admin().indices().prepareAliases().addAlias("test1", "bars", termFilter("name", "bar"))); + assertAcked(admin().indices().prepareAliases().addAlias("test1", "foos", termQuery("name", "foo"))); + assertAcked(admin().indices().prepareAliases().addAlias("test1", "bars", termQuery("name", "bar"))); logger.info("--> adding filtering aliases to index [test2]"); assertAcked(admin().indices().prepareAliases().addAlias("test2", "aliasToTest2")); assertAcked(admin().indices().prepareAliases().addAlias("test2", "aliasToTests")); - assertAcked(admin().indices().prepareAliases().addAlias("test2", "foos", termFilter("name", "foo"))); + assertAcked(admin().indices().prepareAliases().addAlias("test2", "foos", termQuery("name", "foo"))); logger.info("--> indexing against [test1]"); client().index(indexRequest("test1").type("type1").id("1").source(source("1", "foo test"))).get(); @@ -319,13 +334,13 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { assertAcked(admin().indices().prepareAliases().addAlias("test2", "alias12")); logger.info("--> adding filtering aliases to indices"); - assertAcked(admin().indices().prepareAliases().addAlias("test1", "filter1", termFilter("name", "test1"))); + assertAcked(admin().indices().prepareAliases().addAlias("test1", "filter1", termQuery("name", "test1"))); - assertAcked(admin().indices().prepareAliases().addAlias("test2", "filter23", termFilter("name", "foo"))); - assertAcked(admin().indices().prepareAliases().addAlias("test3", "filter23", termFilter("name", "foo"))); + assertAcked(admin().indices().prepareAliases().addAlias("test2", "filter23", termQuery("name", "foo"))); + assertAcked(admin().indices().prepareAliases().addAlias("test3", "filter23", termQuery("name", "foo"))); - assertAcked(admin().indices().prepareAliases().addAlias("test1", "filter13", termFilter("name", "baz"))); - assertAcked(admin().indices().prepareAliases().addAlias("test3", "filter13", termFilter("name", "baz"))); + assertAcked(admin().indices().prepareAliases().addAlias("test1", "filter13", termQuery("name", "baz"))); + assertAcked(admin().indices().prepareAliases().addAlias("test3", "filter13", termQuery("name", "baz"))); logger.info("--> indexing against [test1]"); client().index(indexRequest("test1").type("type1").id("11").source(source("11", "foo test1"))).get(); @@ -378,15 +393,15 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { logger.info("--> adding filtering aliases to index [test1]"); assertAcked(admin().indices().prepareAliases().addAlias("test1", "aliasToTest1")); assertAcked(admin().indices().prepareAliases().addAlias("test1", "aliasToTests")); - assertAcked(admin().indices().prepareAliases().addAlias("test1", "foos", termFilter("name", "foo"))); - assertAcked(admin().indices().prepareAliases().addAlias("test1", "bars", termFilter("name", "bar"))); - assertAcked(admin().indices().prepareAliases().addAlias("test1", "tests", termFilter("name", "test"))); + assertAcked(admin().indices().prepareAliases().addAlias("test1", "foos", termQuery("name", "foo"))); + assertAcked(admin().indices().prepareAliases().addAlias("test1", "bars", termQuery("name", "bar"))); + assertAcked(admin().indices().prepareAliases().addAlias("test1", "tests", termQuery("name", "test"))); logger.info("--> adding filtering aliases to index [test2]"); assertAcked(admin().indices().prepareAliases().addAlias("test2", "aliasToTest2")); assertAcked(admin().indices().prepareAliases().addAlias("test2", "aliasToTests")); - assertAcked(admin().indices().prepareAliases().addAlias("test2", "foos", termFilter("name", "foo"))); - assertAcked(admin().indices().prepareAliases().addAlias("test2", "tests", termFilter("name", "test"))); + assertAcked(admin().indices().prepareAliases().addAlias("test2", "foos", termQuery("name", "foo"))); + assertAcked(admin().indices().prepareAliases().addAlias("test2", "tests", termQuery("name", "test"))); logger.info("--> indexing against [test1]"); client().index(indexRequest("test1").type("type1").id("1").source(source("1", "foo test"))).get(); @@ -418,15 +433,15 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { logger.info("--> adding filtering aliases to index [test1]"); assertAcked(admin().indices().prepareAliases().addAlias("test1", "aliasToTest1") .addAlias("test1", "aliasToTests") - .addAlias("test1", "foos", termFilter("name", "foo")) - .addAlias("test1", "bars", termFilter("name", "bar")) - .addAlias("test1", "tests", termFilter("name", "test"))); + .addAlias("test1", "foos", termQuery("name", "foo")) + .addAlias("test1", "bars", termQuery("name", "bar")) + .addAlias("test1", "tests", termQuery("name", "test"))); logger.info("--> adding filtering aliases to index [test2]"); assertAcked(admin().indices().prepareAliases().addAlias("test2", "aliasToTest2") .addAlias("test2", "aliasToTests") - .addAlias("test2", "foos", termFilter("name", "foo")) - .addAlias("test2", "tests", termFilter("name", "test"))); + .addAlias("test2", "foos", termQuery("name", "foo")) + .addAlias("test2", "tests", termQuery("name", "test"))); String[] indices = {"test1", "test2"}; String[] aliases = {"aliasToTest1", "foos", "bars", "tests", "aliasToTest2", "aliasToTests"}; @@ -510,17 +525,17 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { logger.info("--> modifying alias1 to have a filter"); stopWatch.start(); - assertAcked((admin().indices().prepareAliases().addAlias("test", "alias1", termFilter("name", "foo")).setTimeout(timeout))); + assertAcked((admin().indices().prepareAliases().addAlias("test", "alias1", termQuery("name", "foo")).setTimeout(timeout))); assertThat(stopWatch.stop().lastTaskTime().millis(), lessThan(timeout.millis())); logger.info("--> recreating alias1 with the same filter"); stopWatch.start(); - assertAcked((admin().indices().prepareAliases().addAlias("test", "alias1", termFilter("name", "foo")).setTimeout(timeout))); + assertAcked((admin().indices().prepareAliases().addAlias("test", "alias1", termQuery("name", "foo")).setTimeout(timeout))); assertThat(stopWatch.stop().lastTaskTime().millis(), lessThan(timeout.millis())); logger.info("--> recreating alias1 with a different filter"); stopWatch.start(); - assertAcked((admin().indices().prepareAliases().addAlias("test", "alias1", termFilter("name", "bar")).setTimeout(timeout))); + assertAcked((admin().indices().prepareAliases().addAlias("test", "alias1", termQuery("name", "bar")).setTimeout(timeout))); assertThat(stopWatch.stop().lastTaskTime().millis(), lessThan(timeout.millis())); logger.info("--> verify that filter was updated"); @@ -602,7 +617,7 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { logger.info("--> creating aliases [bar, baz, foo]"); assertAcked(admin().indices().prepareAliases() .addAlias("bazbar", "bar") - .addAlias("bazbar", "bac", termFilter("field", "value")) + .addAlias("bazbar", "bac", termQuery("field", "value")) .addAlias("foobar", "foo")); assertAcked(admin().indices().prepareAliases() @@ -863,7 +878,7 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { assertAcked(prepareCreate("test") .addMapping("type", "field", "type=string") .addAlias(new Alias("alias1")) - .addAlias(new Alias("alias2").filter(FilterBuilders.missingFilter("field"))) + .addAlias(new Alias("alias2").filter(QueryBuilders.missingQuery("field"))) .addAlias(new Alias("alias3").indexRouting("index").searchRouting("search"))); checkAliases(); @@ -924,7 +939,7 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { try { client().admin().indices().prepareAliases() - .addAlias("test", "a", FilterBuilders.termFilter("field1", "term")) + .addAlias("test", "a", QueryBuilders.termQuery("field1", "term")) .get(); fail(); } catch (IllegalArgumentException e) { @@ -933,7 +948,7 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { try { client().admin().indices().prepareAliases() - .addAlias("test", "a", FilterBuilders.rangeFilter("field2").from(0).to(1)) + .addAlias("test", "a", QueryBuilders.rangeQuery("field2").from(0).to(1)) .get(); fail(); } catch (IllegalArgumentException e) { @@ -941,15 +956,15 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { } client().admin().indices().prepareAliases() - .addAlias("test", "a", FilterBuilders.matchAllFilter()) // <-- no fail, b/c no field mentioned + .addAlias("test", "a", QueryBuilders.matchAllQuery()) // <-- no fail, b/c no field mentioned .get(); } @Test public void testAliasFilterWithNowInRangeFilterAndQuery() throws Exception { assertAcked(prepareCreate("my-index").addMapping("my-type", "_timestamp", "enabled=true")); - assertAcked(admin().indices().prepareAliases().addAlias("my-index", "filter1", rangeFilter("_timestamp").from("now-1d").to("now"))); - assertAcked(admin().indices().prepareAliases().addAlias("my-index", "filter2", queryFilter(rangeQuery("_timestamp").from("now-1d").to("now")))); + assertAcked(admin().indices().prepareAliases().addAlias("my-index", "filter1", rangeQuery("_timestamp").from("now-1d").to("now"))); + assertAcked(admin().indices().prepareAliases().addAlias("my-index", "filter2", rangeQuery("_timestamp").from("now-1d").to("now"))); final int numDocs = scaledRandomIntBetween(5, 52); for (int i = 1; i <= numDocs; i++) { @@ -971,8 +986,8 @@ public class IndexAliasesTests extends ElasticsearchIntegrationTest { .addMapping("parent") .addMapping("child", "_parent", "type=parent") ); - assertAcked(admin().indices().prepareAliases().addAlias("my-index", "filter1", hasChildFilter("child", matchAllQuery()))); - assertAcked(admin().indices().prepareAliases().addAlias("my-index", "filter2", hasParentFilter("child", matchAllQuery()))); + assertAcked(admin().indices().prepareAliases().addAlias("my-index", "filter1", hasChildQuery("child", matchAllQuery()))); + assertAcked(admin().indices().prepareAliases().addAlias("my-index", "filter2", hasParentQuery("child", matchAllQuery()))); } @Test diff --git a/src/test/java/org/elasticsearch/benchmark/scripts/score/BasicScriptBenchmark.java b/src/test/java/org/elasticsearch/benchmark/scripts/score/BasicScriptBenchmark.java index 79b009e2010..054a16439aa 100644 --- a/src/test/java/org/elasticsearch/benchmark/scripts/score/BasicScriptBenchmark.java +++ b/src/test/java/org/elasticsearch/benchmark/scripts/score/BasicScriptBenchmark.java @@ -30,7 +30,7 @@ import org.elasticsearch.common.lucene.search.function.CombineFunction; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.functionscore.script.ScriptScoreFunctionBuilder; import org.joda.time.DateTime; @@ -284,7 +284,7 @@ public class BasicScriptBenchmark { searchSource() .explain(false) .size(0) - .query(functionScoreQuery(FilterBuilders.termsFilter("text", terms), scriptFunction).boostMode( + .query(functionScoreQuery(QueryBuilders.termsQuery("text", terms), scriptFunction).boostMode( CombineFunction.REPLACE))); nativeSearchRequests.add(new AbstractMap.SimpleEntry<>(infoString, new RequestInfo(request, nTerms + 1))); } @@ -297,7 +297,7 @@ public class BasicScriptBenchmark { ScriptScoreFunctionBuilder scriptFunction = (langNative == true) ? scriptFunction(script, "native") : scriptFunction(script); SearchRequest request = searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource().explain(false).size(0) - .query(functionScoreQuery(FilterBuilders.matchAllFilter(), scriptFunction).boostMode(CombineFunction.REPLACE))); + .query(functionScoreQuery(QueryBuilders.matchAllQuery(), scriptFunction).boostMode(CombineFunction.REPLACE))); nativeSearchRequests.add(new AbstractMap.SimpleEntry<>(infoString, new RequestInfo(request, 0))); return nativeSearchRequests; diff --git a/src/test/java/org/elasticsearch/benchmark/search/aggregations/QueryFilterAggregationSearchBenchmark.java b/src/test/java/org/elasticsearch/benchmark/search/aggregations/QueryFilterAggregationSearchBenchmark.java index 99894018e62..a8a6ec35794 100644 --- a/src/test/java/org/elasticsearch/benchmark/search/aggregations/QueryFilterAggregationSearchBenchmark.java +++ b/src/test/java/org/elasticsearch/benchmark/search/aggregations/QueryFilterAggregationSearchBenchmark.java @@ -30,7 +30,7 @@ import org.elasticsearch.common.StopWatch; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.SizeValue; import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.node.Node; import org.elasticsearch.search.aggregations.AggregationBuilders; @@ -138,7 +138,7 @@ public class QueryFilterAggregationSearchBenchmark { SearchResponse searchResponse = client.prepareSearch() .setSize(0) .setQuery(termQuery("l_value", anyValue)) - .addAggregation(AggregationBuilders.filter("filter").filter(FilterBuilders.termFilter("l_value", anyValue))) + .addAggregation(AggregationBuilders.filter("filter").filter(QueryBuilders.termQuery("l_value", anyValue))) .execute().actionGet(); totalQueryTime += searchResponse.getTookInMillis(); } diff --git a/src/test/java/org/elasticsearch/benchmark/search/aggregations/TimeDataHistogramAggregationBenchmark.java b/src/test/java/org/elasticsearch/benchmark/search/aggregations/TimeDataHistogramAggregationBenchmark.java index 8445f8a1f45..32f34ec5c96 100644 --- a/src/test/java/org/elasticsearch/benchmark/search/aggregations/TimeDataHistogramAggregationBenchmark.java +++ b/src/test/java/org/elasticsearch/benchmark/search/aggregations/TimeDataHistogramAggregationBenchmark.java @@ -35,7 +35,7 @@ import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.index.fielddata.IndexFieldData; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.indices.IndexAlreadyExistsException; import org.elasticsearch.node.Node; @@ -210,7 +210,7 @@ public class TimeDataHistogramAggregationBenchmark { private static SearchResponse doTermsAggsSearch(String name, String field, float matchPercentage) { SearchResponse response = client.prepareSearch() .setSize(0) - .setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.scriptFilter("random() 0) { diff --git a/src/test/java/org/elasticsearch/benchmark/search/child/ChildSearchShortCircuitBenchmark.java b/src/test/java/org/elasticsearch/benchmark/search/child/ChildSearchShortCircuitBenchmark.java index 77bf13ba57a..d13f8fb095d 100644 --- a/src/test/java/org/elasticsearch/benchmark/search/child/ChildSearchShortCircuitBenchmark.java +++ b/src/test/java/org/elasticsearch/benchmark/search/child/ChildSearchShortCircuitBenchmark.java @@ -40,8 +40,10 @@ import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.hasChildFilter; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; +import static org.elasticsearch.index.query.QueryBuilders.hasChildQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchQuery; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; /** @@ -156,7 +158,7 @@ public class ChildSearchShortCircuitBenchmark { for (int i = 1; i < PARENT_COUNT; i *= 2) { for (int j = 0; j < QUERY_COUNT; j++) { SearchResponse searchResponse = client.prepareSearch(indexName) - .setQuery(filteredQuery(matchAllQuery(), hasChildFilter("child", matchQuery("field2", i)))) + .setQuery(filteredQuery(matchAllQuery(), hasChildQuery("child", matchQuery("field2", i)))) .execute().actionGet(); if (searchResponse.getHits().totalHits() != i) { System.err.println("--> mismatch on hits"); diff --git a/src/test/java/org/elasticsearch/benchmark/search/geo/GeoDistanceSearchBenchmark.java b/src/test/java/org/elasticsearch/benchmark/search/geo/GeoDistanceSearchBenchmark.java index 5d30c389a8d..c73bbd75f10 100644 --- a/src/test/java/org/elasticsearch/benchmark/search/geo/GeoDistanceSearchBenchmark.java +++ b/src/test/java/org/elasticsearch/benchmark/search/geo/GeoDistanceSearchBenchmark.java @@ -31,7 +31,7 @@ import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.geoDistanceFilter; +import static org.elasticsearch.index.query.QueryBuilders.geoDistanceQuery; import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; @@ -192,7 +192,7 @@ public class GeoDistanceSearchBenchmark { public static void run(Client client, GeoDistance geoDistance, String optimizeBbox) { client.prepareSearch() // from NY .setSize(0) - .setQuery(filteredQuery(matchAllQuery(), geoDistanceFilter("location") + .setQuery(filteredQuery(matchAllQuery(), geoDistanceQuery("location") .distance("2km") .optimizeBbox(optimizeBbox) .geoDistance(geoDistance) diff --git a/src/test/java/org/elasticsearch/benchmark/stress/NodesStressTest.java b/src/test/java/org/elasticsearch/benchmark/stress/NodesStressTest.java index fab0166e4b8..ed72fa24395 100644 --- a/src/test/java/org/elasticsearch/benchmark/stress/NodesStressTest.java +++ b/src/test/java/org/elasticsearch/benchmark/stress/NodesStressTest.java @@ -36,9 +36,8 @@ import java.util.concurrent.atomic.AtomicLong; import static org.elasticsearch.client.Requests.searchRequest; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; -import static org.elasticsearch.common.settings.ImmutableSettings.Builder.EMPTY_SETTINGS; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; -import static org.elasticsearch.index.query.FilterBuilders.queryFilter; +import static org.elasticsearch.common.settings.ImmutableSettings.Builder.EMPTY_SETTINGS; import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; @@ -207,7 +206,7 @@ public class NodesStressTest { for (; counter < max; counter++) { Client client = client(counter); QueryBuilder query = termQuery("num", counter % fieldNumLimit); - query = constantScoreQuery(queryFilter(query)); + query = constantScoreQuery(query); SearchResponse search = client.search(searchRequest() .source(searchSource().query(query))) diff --git a/src/test/java/org/elasticsearch/bwcompat/BasicBackwardsCompatibilityTest.java b/src/test/java/org/elasticsearch/bwcompat/BasicBackwardsCompatibilityTest.java index 05723ac1b69..f1a7788f0d7 100644 --- a/src/test/java/org/elasticsearch/bwcompat/BasicBackwardsCompatibilityTest.java +++ b/src/test/java/org/elasticsearch/bwcompat/BasicBackwardsCompatibilityTest.java @@ -69,8 +69,8 @@ import java.util.List; import java.util.concurrent.ExecutionException; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.existsFilter; -import static org.elasticsearch.index.query.FilterBuilders.missingFilter; +import static org.elasticsearch.index.query.QueryBuilders.existsQuery; +import static org.elasticsearch.index.query.QueryBuilders.missingQuery; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; import static org.hamcrest.Matchers.*; @@ -417,47 +417,47 @@ public class BasicBackwardsCompatibilityTest extends ElasticsearchBackwardsCompa client().prepareIndex(indexName, "type1", "3").setSource(jsonBuilder().startObject().startObject("obj2").field("obj2_val", "1").endObject().field("y1", "y_1").field("field2", "value2_3").endObject()), client().prepareIndex(indexName, "type1", "4").setSource(jsonBuilder().startObject().startObject("obj2").field("obj2_val", "1").endObject().field("y2", "y_2").field("field3", "value3_4").endObject())); - CountResponse countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("field1"))).get(); + CountResponse countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsQuery("field1"))).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(constantScoreQuery(existsFilter("field1"))).get(); + countResponse = client().prepareCount().setQuery(constantScoreQuery(existsQuery("field1"))).get(); assertHitCount(countResponse, 2l); countResponse = client().prepareCount().setQuery(queryStringQuery("_exists_:field1")).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("field2"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsQuery("field2"))).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("field3"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsQuery("field3"))).get(); assertHitCount(countResponse, 1l); // wildcard check - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("x*"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsQuery("x*"))).get(); assertHitCount(countResponse, 2l); // object check - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("obj1"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsQuery("obj1"))).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("field1"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingQuery("field1"))).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("field1"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingQuery("field1"))).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(constantScoreQuery(missingFilter("field1"))).get(); + countResponse = client().prepareCount().setQuery(constantScoreQuery(missingQuery("field1"))).get(); assertHitCount(countResponse, 2l); countResponse = client().prepareCount().setQuery(queryStringQuery("_missing_:field1")).get(); assertHitCount(countResponse, 2l); // wildcard check - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("x*"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingQuery("x*"))).get(); assertHitCount(countResponse, 2l); // object check - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("obj1"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingQuery("obj1"))).get(); assertHitCount(countResponse, 2l); if (!backwardsCluster().upgradeOneNode()) { break; diff --git a/src/test/java/org/elasticsearch/bwcompat/OldIndexBackwardsCompatibilityTests.java b/src/test/java/org/elasticsearch/bwcompat/OldIndexBackwardsCompatibilityTests.java index 75f2eb1a6f2..300b7ae6707 100644 --- a/src/test/java/org/elasticsearch/bwcompat/OldIndexBackwardsCompatibilityTests.java +++ b/src/test/java/org/elasticsearch/bwcompat/OldIndexBackwardsCompatibilityTests.java @@ -38,7 +38,7 @@ import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.env.NodeEnvironment; import org.elasticsearch.index.engine.EngineConfig; import org.elasticsearch.index.merge.policy.MergePolicyModule; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.indices.recovery.RecoverySettings; import org.elasticsearch.node.Node; @@ -302,14 +302,14 @@ public class OldIndexBackwardsCompatibilityTests extends ElasticsearchIntegratio ElasticsearchAssertions.assertNoFailures(searchReq.get()); logger.info("--> testing exists filter"); - searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.existsFilter("string"))); + searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), QueryBuilders.existsQuery("string"))); searchRsp = searchReq.get(); ElasticsearchAssertions.assertNoFailures(searchRsp); assertEquals(numDocs, searchRsp.getHits().getTotalHits()); logger.info("--> testing missing filter"); // the field for the missing filter here needs to be different than the exists filter above, to avoid being found in the cache - searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.missingFilter("long_sort"))); + searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), QueryBuilders.missingQuery("long_sort"))); searchRsp = searchReq.get(); ElasticsearchAssertions.assertNoFailures(searchRsp); assertEquals(0, searchRsp.getHits().getTotalHits()); diff --git a/src/test/java/org/elasticsearch/cluster/ClusterStateDiffTests.java b/src/test/java/org/elasticsearch/cluster/ClusterStateDiffTests.java index b49b7586dc3..4832e380abb 100644 --- a/src/test/java/org/elasticsearch/cluster/ClusterStateDiffTests.java +++ b/src/test/java/org/elasticsearch/cluster/ClusterStateDiffTests.java @@ -39,7 +39,7 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.LocalTransportAddress; import org.elasticsearch.discovery.DiscoverySettings; import org.elasticsearch.gateway.GatewayService; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.search.warmer.IndexWarmersMetaData; import org.elasticsearch.test.ElasticsearchIntegrationTest; @@ -464,7 +464,7 @@ public class ClusterStateDiffTests extends ElasticsearchIntegrationTest { private AliasMetaData randomAlias() { AliasMetaData.Builder builder = newAliasMetaDataBuilder(randomName("alias")); if (randomBoolean()) { - builder.filter(FilterBuilders.termFilter("test", randomRealisticUnicodeOfCodepointLength(10)).toString()); + builder.filter(QueryBuilders.termQuery("test", randomRealisticUnicodeOfCodepointLength(10)).toString()); } if (randomBoolean()) { builder.routing(randomAsciiOfLength(10)); diff --git a/src/test/java/org/elasticsearch/cluster/SpecificMasterNodesTests.java b/src/test/java/org/elasticsearch/cluster/SpecificMasterNodesTests.java index 6defc2c3ebf..0351f0613b6 100644 --- a/src/test/java/org/elasticsearch/cluster/SpecificMasterNodesTests.java +++ b/src/test/java/org/elasticsearch/cluster/SpecificMasterNodesTests.java @@ -22,7 +22,7 @@ package org.elasticsearch.cluster; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.discovery.MasterNotDiscoveredException; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope; import org.junit.Test; @@ -136,6 +136,6 @@ public class SpecificMasterNodesTests extends ElasticsearchIntegrationTest { internalCluster().startNode(settingsBuilder().put("node.data", true).put("node.master", false)); assertAcked(prepareCreate("test").addMapping("type1", "{\"type1\" : {\"properties\" : {\"table_a\" : { \"type\" : \"nested\", \"properties\" : {\"field_a\" : { \"type\" : \"string\" },\"field_b\" :{ \"type\" : \"string\" }}}}}}")); - client().admin().indices().prepareAliases().addAlias("test", "a_test", FilterBuilders.nestedFilter("table_a", FilterBuilders.termFilter("table_a.field_b", "y"))).get(); + client().admin().indices().prepareAliases().addAlias("test", "a_test", QueryBuilders.nestedQuery("table_a", QueryBuilders.termQuery("table_a.field_b", "y"))).get(); } } diff --git a/src/test/java/org/elasticsearch/common/lucene/index/FreqTermsEnumTests.java b/src/test/java/org/elasticsearch/common/lucene/index/FreqTermsEnumTests.java index 5aabe4a594c..02468f98cee 100644 --- a/src/test/java/org/elasticsearch/common/lucene/index/FreqTermsEnumTests.java +++ b/src/test/java/org/elasticsearch/common/lucene/index/FreqTermsEnumTests.java @@ -37,6 +37,7 @@ import org.apache.lucene.index.NoMergePolicy; import org.apache.lucene.index.Term; import org.apache.lucene.queries.TermsQuery; import org.apache.lucene.search.Filter; +import org.apache.lucene.search.Query; import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.store.Directory; import org.apache.lucene.util.BytesRef; @@ -191,9 +192,9 @@ public class FreqTermsEnumTests extends ElasticsearchTestCase { @Test public void testNonDeletedFreqs() throws Exception { - assertAgainstReference(true, true, Queries.newMatchAllFilter(), referenceNotDeleted); - assertAgainstReference(true, false, Queries.newMatchAllFilter(), referenceNotDeleted); - assertAgainstReference(false, true, Queries.newMatchAllFilter(), referenceNotDeleted); + assertAgainstReference(true, true, Queries.newMatchAllQuery(), referenceNotDeleted); + assertAgainstReference(true, false, Queries.newMatchAllQuery(), referenceNotDeleted); + assertAgainstReference(false, true, Queries.newMatchAllQuery(), referenceNotDeleted); } @Test @@ -203,7 +204,7 @@ public class FreqTermsEnumTests extends ElasticsearchTestCase { assertAgainstReference(false, true, filter, referenceFilter); } - private void assertAgainstReference(boolean docFreq, boolean totalTermFreq, Filter filter, Map reference) throws Exception { + private void assertAgainstReference(boolean docFreq, boolean totalTermFreq, Query filter, Map reference) throws Exception { FreqTermsEnum freqTermsEnum = new FreqTermsEnum(reader, "field", docFreq, totalTermFreq, filter, BigArrays.NON_RECYCLING_INSTANCE); assertAgainstReference(freqTermsEnum, reference, docFreq, totalTermFreq); } diff --git a/src/test/java/org/elasticsearch/common/lucene/search/MatchAllDocsFilterTests.java b/src/test/java/org/elasticsearch/common/lucene/search/MatchAllDocsFilterTests.java deleted file mode 100644 index 10f10ff0cc2..00000000000 --- a/src/test/java/org/elasticsearch/common/lucene/search/MatchAllDocsFilterTests.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.common.lucene.search; - -import org.apache.lucene.document.Document; -import org.apache.lucene.document.Field; -import org.apache.lucene.document.TextField; -import org.apache.lucene.index.DirectoryReader; -import org.apache.lucene.index.IndexReader; -import org.apache.lucene.index.IndexWriter; -import org.apache.lucene.index.IndexWriterConfig; -import org.apache.lucene.search.ConstantScoreQuery; -import org.apache.lucene.search.IndexSearcher; -import org.apache.lucene.store.Directory; -import org.apache.lucene.store.RAMDirectory; -import org.elasticsearch.common.lucene.Lucene; -import org.elasticsearch.test.ElasticsearchTestCase; -import org.junit.Test; - -import static org.hamcrest.Matchers.equalTo; - -/** - * - */ -public class MatchAllDocsFilterTests extends ElasticsearchTestCase { - - @Test - public void testMatchAllDocsFilter() throws Exception { - Directory dir = new RAMDirectory(); - IndexWriter indexWriter = new IndexWriter(dir, new IndexWriterConfig(Lucene.STANDARD_ANALYZER)); - - Document document = new Document(); - document.add(new TextField("_id", "1", Field.Store.YES)); - document.add(new TextField("text", "lucene", Field.Store.YES)); - indexWriter.addDocument(document); - - document = new Document(); - document.add(new TextField("_id", "2", Field.Store.YES)); - document.add(new TextField("text", "lucene release", Field.Store.YES)); - indexWriter.addDocument(document); - - IndexReader reader = DirectoryReader.open(indexWriter, true); - IndexSearcher searcher = new IndexSearcher(reader); - - ConstantScoreQuery query = new ConstantScoreQuery(Queries.newMatchAllFilter()); - long count = Lucene.count(searcher, query); - assertThat(count, equalTo(2l)); - - reader.close(); - indexWriter.close(); - } -} diff --git a/src/test/java/org/elasticsearch/count/query/CountQueryTests.java b/src/test/java/org/elasticsearch/count/query/CountQueryTests.java index d06c2613e19..e06b8fa607d 100644 --- a/src/test/java/org/elasticsearch/count/query/CountQueryTests.java +++ b/src/test/java/org/elasticsearch/count/query/CountQueryTests.java @@ -19,7 +19,6 @@ package org.elasticsearch.count.query; -import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; import org.elasticsearch.action.ShardOperationFailedException; import org.elasticsearch.action.count.CountResponse; @@ -28,9 +27,14 @@ import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.*; +import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.CommonTermsQueryBuilder.Operator; +import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.index.query.MatchQueryBuilder.Type; +import org.elasticsearch.index.query.MultiMatchQueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.index.query.TermQueryBuilder; +import org.elasticsearch.index.query.WrapperQueryBuilder; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.joda.time.DateTime; @@ -42,10 +46,28 @@ import java.io.IOException; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.*; -import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; -import static org.hamcrest.Matchers.*; +import static org.elasticsearch.index.query.QueryBuilders.boolQuery; +import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; +import static org.elasticsearch.index.query.QueryBuilders.existsQuery; +import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; +import static org.elasticsearch.index.query.QueryBuilders.idsQuery; +import static org.elasticsearch.index.query.QueryBuilders.limitQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchQuery; +import static org.elasticsearch.index.query.QueryBuilders.missingQuery; +import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery; +import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; +import static org.elasticsearch.index.query.QueryBuilders.termsLookupQuery; +import static org.elasticsearch.index.query.QueryBuilders.termsQuery; +import static org.elasticsearch.index.query.QueryBuilders.typeQuery; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; public class CountQueryTests extends ElasticsearchIntegrationTest { @@ -241,8 +263,8 @@ public class CountQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type2", "2").setSource("field1", "value1"), client().prepareIndex("test", "type2", "3").setSource("field1", "value1")); - assertHitCount(client().prepareCount().setQuery(filteredQuery(matchAllQuery(), typeFilter("type1"))).get(), 2l); - assertHitCount(client().prepareCount().setQuery(filteredQuery(matchAllQuery(), typeFilter("type2"))).get(), 3l); + assertHitCount(client().prepareCount().setQuery(filteredQuery(matchAllQuery(), typeQuery("type1"))).get(), 2l); + assertHitCount(client().prepareCount().setQuery(filteredQuery(matchAllQuery(), typeQuery("type2"))).get(), 3l); assertHitCount(client().prepareCount().setTypes("type1").setQuery(matchAllQuery()).get(), 2l); assertHitCount(client().prepareCount().setTypes("type2").setQuery(matchAllQuery()).get(), 3l); @@ -251,16 +273,16 @@ public class CountQueryTests extends ElasticsearchIntegrationTest { } @Test - public void idsFilterTestsIdIndexed() throws Exception { - idsFilterTests("not_analyzed"); + public void idsQueryTestsIdIndexed() throws Exception { + idsQueryTests("not_analyzed"); } @Test - public void idsFilterTestsIdNotIndexed() throws Exception { - idsFilterTests("no"); + public void idsQueryTestsIdNotIndexed() throws Exception { + idsQueryTests("no"); } - private void idsFilterTests(String index) throws Exception { + private void idsQueryTests(String index) throws Exception { Settings indexSettings = ImmutableSettings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.V_1_4_2.id).build(); assertAcked(prepareCreate("test").setSettings(indexSettings) .addMapping("type1", jsonBuilder().startObject().startObject("type1") @@ -271,11 +293,11 @@ public class CountQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type1", "2").setSource("field1", "value2"), client().prepareIndex("test", "type1", "3").setSource("field1", "value3")); - CountResponse countResponse = client().prepareCount().setQuery(constantScoreQuery(idsFilter("type1").ids("1", "3"))).get(); + CountResponse countResponse = client().prepareCount().setQuery(constantScoreQuery(idsQuery("type1").ids("1", "3"))).get(); assertHitCount(countResponse, 2l); // no type - countResponse = client().prepareCount().setQuery(constantScoreQuery(idsFilter().ids("1", "3"))).get(); + countResponse = client().prepareCount().setQuery(constantScoreQuery(idsQuery().ids("1", "3"))).get(); assertHitCount(countResponse, 2l); countResponse = client().prepareCount().setQuery(idsQuery("type1").ids("1", "3")).get(); @@ -289,7 +311,7 @@ public class CountQueryTests extends ElasticsearchIntegrationTest { assertHitCount(countResponse, 0l); // repeat..., with terms - countResponse = client().prepareCount().setTypes("type1").setQuery(constantScoreQuery(termsFilter("_id", "1", "3"))).get(); + countResponse = client().prepareCount().setTypes("type1").setQuery(constantScoreQuery(termsQuery("_id", "1", "3"))).get(); assertHitCount(countResponse, 2l); } @@ -302,7 +324,7 @@ public class CountQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type1", "3").setSource("field2", "value2_3"), client().prepareIndex("test", "type1", "4").setSource("field3", "value3_4")); - CountResponse countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), limitFilter(2))).get(); + CountResponse countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), limitQuery(2))).get(); assertHitCount(countResponse, 4l); // limit is a no-op } @@ -316,47 +338,47 @@ public class CountQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type1", "3").setSource(jsonBuilder().startObject().startObject("obj2").field("obj2_val", "1").endObject().field("y1", "y_1").field("field2", "value2_3").endObject()), client().prepareIndex("test", "type1", "4").setSource(jsonBuilder().startObject().startObject("obj2").field("obj2_val", "1").endObject().field("y2", "y_2").field("field3", "value3_4").endObject())); - CountResponse countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("field1"))).get(); + CountResponse countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsQuery("field1"))).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(constantScoreQuery(existsFilter("field1"))).get(); + countResponse = client().prepareCount().setQuery(constantScoreQuery(existsQuery("field1"))).get(); assertHitCount(countResponse, 2l); countResponse = client().prepareCount().setQuery(queryStringQuery("_exists_:field1")).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("field2"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsQuery("field2"))).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("field3"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsQuery("field3"))).get(); assertHitCount(countResponse, 1l); // wildcard check - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("x*"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsQuery("x*"))).get(); assertHitCount(countResponse, 2l); // object check - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("obj1"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsQuery("obj1"))).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("field1"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingQuery("field1"))).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("field1"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingQuery("field1"))).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(constantScoreQuery(missingFilter("field1"))).get(); + countResponse = client().prepareCount().setQuery(constantScoreQuery(missingQuery("field1"))).get(); assertHitCount(countResponse, 2l); countResponse = client().prepareCount().setQuery(queryStringQuery("_missing_:field1")).get(); assertHitCount(countResponse, 2l); // wildcard check - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("x*"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingQuery("x*"))).get(); assertHitCount(countResponse, 2l); // object check - countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("obj1"))).get(); + countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingQuery("obj1"))).get(); assertHitCount(countResponse, 2l); } @@ -572,11 +594,11 @@ public class CountQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type", "4").setSource("term", "4").get(); refresh(); CountResponse countResponse = client().prepareCount("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("term", new String[0]))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("term", new String[0]))).get(); assertHitCount(countResponse, 0l); countResponse = client().prepareCount("test") - .setQuery(filteredQuery(matchAllQuery(), idsFilter())).get(); + .setQuery(filteredQuery(matchAllQuery(), idsQuery())).get(); assertHitCount(countResponse, 0l); } @@ -617,47 +639,47 @@ public class CountQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type", "4").setSource("term", "4")); CountResponse countResponse = client().prepareCount("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms"))).get(); assertHitCount(countResponse, 2l); // same as above, just on the _id... countResponse = client().prepareCount("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("_id").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("_id").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms"))).get(); assertHitCount(countResponse, 2l); // another search with same parameters... countResponse = client().prepareCount("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms"))).get(); assertHitCount(countResponse, 2l); countResponse = client().prepareCount("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("2").lookupPath("terms"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup").lookupType("type").lookupId("2").lookupPath("terms"))).get(); assertHitCount(countResponse, 1l); countResponse = client().prepareCount("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("3").lookupPath("terms")) + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup").lookupType("type").lookupId("3").lookupPath("terms")) ).get(); assertNoFailures(countResponse); assertHitCount(countResponse, 2l); countResponse = client().prepareCount("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("4").lookupPath("terms"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup").lookupType("type").lookupId("4").lookupPath("terms"))).get(); assertHitCount(countResponse, 0l); countResponse = client().prepareCount("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup2").lookupType("type").lookupId("1").lookupPath("arr.term"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup2").lookupType("type").lookupId("1").lookupPath("arr.term"))).get(); assertHitCount(countResponse, 2l); countResponse = client().prepareCount("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup2").lookupType("type").lookupId("2").lookupPath("arr.term"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup2").lookupType("type").lookupId("2").lookupPath("arr.term"))).get(); assertHitCount(countResponse, 1l); countResponse = client().prepareCount("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup2").lookupType("type").lookupId("3").lookupPath("arr.term"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup2").lookupType("type").lookupId("3").lookupPath("arr.term"))).get(); assertHitCount(countResponse, 2l); countResponse = client().prepareCount("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("not_exists").lookupIndex("lookup2").lookupType("type").lookupId("3").lookupPath("arr.term"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("not_exists").lookupIndex("lookup2").lookupType("type").lookupId("3").lookupPath("arr.term"))).get(); assertHitCount(countResponse, 0l); } @@ -670,22 +692,22 @@ public class CountQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type2", "2").setSource("field1", "value2").get(); refresh(); - CountResponse countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter("type1", "type2").ids("1", "2"))).get(); + CountResponse countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery("type1", "type2").ids("1", "2"))).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter().ids("1", "2"))).get(); + countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().ids("1", "2"))).get(); assertHitCount(countResponse, 2l); - countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter("type1").ids("1", "2"))).get(); + countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery("type1").ids("1", "2"))).get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter().ids("1"))).get(); + countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().ids("1"))).get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter(null).ids("1"))).get(); + countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery(null).ids("1"))).get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter("type1", "type2", "type3").ids("1", "2", "3", "4"))).get(); + countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery("type1", "type2", "type3").ids("1", "2", "3", "4"))).get(); assertHitCount(countResponse, 2l); } @@ -769,31 +791,31 @@ public class CountQueryTests extends ElasticsearchIntegrationTest { assertHitCount(countResponse, 1l); logger.info("--> term filter on 1"); - countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_byte", 1))).get(); + countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termQuery("num_byte", 1))).get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_short", 1))).get(); + countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termQuery("num_short", 1))).get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_integer", 1))).get(); + countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termQuery("num_integer", 1))).get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_long", 1))).get(); + countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termQuery("num_long", 1))).get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_float", 1))).get(); + countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termQuery("num_float", 1))).get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_double", 1))).get(); + countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termQuery("num_double", 1))).get(); assertHitCount(countResponse, 1l); logger.info("--> terms filter on 1"); - countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_byte", new int[]{1}))).get(); + countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("num_byte", new int[]{1}))).get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_short", new int[]{1}))).get(); + countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("num_short", new int[]{1}))).get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_integer", new int[]{1}))).get(); + countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("num_integer", new int[]{1}))).get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_long", new int[]{1}))).get(); + countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("num_long", new int[]{1}))).get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_float", new int[]{1}))).get(); + countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("num_float", new int[]{1}))).get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_double", new int[]{1}))).get(); + countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("num_double", new int[]{1}))).get(); assertHitCount(countResponse, 1l); } diff --git a/src/test/java/org/elasticsearch/explain/ExplainActionTests.java b/src/test/java/org/elasticsearch/explain/ExplainActionTests.java index c22d4470875..695e475f6a4 100644 --- a/src/test/java/org/elasticsearch/explain/ExplainActionTests.java +++ b/src/test/java/org/elasticsearch/explain/ExplainActionTests.java @@ -26,7 +26,6 @@ import org.elasticsearch.common.io.stream.InputStreamStreamInput; import org.elasticsearch.common.io.stream.OutputStreamStreamOutput; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.settings.ImmutableSettings; -import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.joda.time.DateTime; @@ -210,7 +209,7 @@ public class ExplainActionTests extends ElasticsearchIntegrationTest { public void testExplainWithFilteredAlias() throws Exception { assertAcked(prepareCreate("test") .addMapping("test", "field2", "type=string") - .addAlias(new Alias("alias1").filter(FilterBuilders.termFilter("field2", "value2")))); + .addAlias(new Alias("alias1").filter(QueryBuilders.termQuery("field2", "value2")))); ensureGreen("test"); client().prepareIndex("test", "test", "1").setSource("field1", "value1", "field2", "value1").get(); @@ -227,7 +226,7 @@ public class ExplainActionTests extends ElasticsearchIntegrationTest { public void testExplainWithFilteredAliasFetchSource() throws Exception { assertAcked(client().admin().indices().prepareCreate("test") .addMapping("test", "field2", "type=string") - .addAlias(new Alias("alias1").filter(FilterBuilders.termFilter("field2", "value2")))); + .addAlias(new Alias("alias1").filter(QueryBuilders.termQuery("field2", "value2")))); ensureGreen("test"); client().prepareIndex("test", "test", "1").setSource("field1", "value1", "field2", "value1").get(); diff --git a/src/test/java/org/elasticsearch/gateway/RecoveryFromGatewayTests.java b/src/test/java/org/elasticsearch/gateway/RecoveryFromGatewayTests.java index 80fce2a8291..b072d8c2ced 100644 --- a/src/test/java/org/elasticsearch/gateway/RecoveryFromGatewayTests.java +++ b/src/test/java/org/elasticsearch/gateway/RecoveryFromGatewayTests.java @@ -29,7 +29,6 @@ import org.elasticsearch.cluster.routing.allocation.decider.ThrottlingAllocation import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.indices.recovery.RecoveryState; import org.elasticsearch.test.ElasticsearchIntegrationTest; @@ -320,7 +319,7 @@ public class RecoveryFromGatewayTests extends ElasticsearchIntegrationTest { .startObject("field2").field("type", "string").field("store", "yes").field("index", "not_analyzed").endObject() .endObject().endObject().endObject()) .execute().actionGet(); - client.admin().indices().prepareAliases().addAlias("test", "test_alias", FilterBuilders.termFilter("field", "value")).execute().actionGet(); + client.admin().indices().prepareAliases().addAlias("test", "test_alias", QueryBuilders.termQuery("field", "value")).execute().actionGet(); logger.info("--> starting two nodes back, verifying we got the latest version"); } diff --git a/src/test/java/org/elasticsearch/index/aliases/IndexAliasesServiceTests.java b/src/test/java/org/elasticsearch/index/aliases/IndexAliasesServiceTests.java index ecf36582437..307179f9f60 100644 --- a/src/test/java/org/elasticsearch/index/aliases/IndexAliasesServiceTests.java +++ b/src/test/java/org/elasticsearch/index/aliases/IndexAliasesServiceTests.java @@ -25,7 +25,7 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.FilterBuilder; +import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.IndexService; import org.elasticsearch.indices.InvalidAliasNameException; import org.elasticsearch.test.ElasticsearchSingleNodeTest; @@ -33,7 +33,7 @@ import org.junit.Test; import java.io.IOException; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; @@ -48,7 +48,7 @@ public class IndexAliasesServiceTests extends ElasticsearchSingleNodeTest { return indexService.aliasesService(); } - public static CompressedString filter(FilterBuilder filterBuilder) throws IOException { + public static CompressedString filter(QueryBuilder filterBuilder) throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder(); filterBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.close(); @@ -58,47 +58,47 @@ public class IndexAliasesServiceTests extends ElasticsearchSingleNodeTest { @Test public void testFilteringAliases() throws Exception { IndexAliasesService indexAliasesService = newIndexAliasesService(); - indexAliasesService.add("cats", filter(termFilter("animal", "cat"))); - indexAliasesService.add("dogs", filter(termFilter("animal", "dog"))); + indexAliasesService.add("cats", filter(termQuery("animal", "cat"))); + indexAliasesService.add("dogs", filter(termQuery("animal", "dog"))); indexAliasesService.add("all", null); assertThat(indexAliasesService.hasAlias("cats"), equalTo(true)); assertThat(indexAliasesService.hasAlias("dogs"), equalTo(true)); assertThat(indexAliasesService.hasAlias("turtles"), equalTo(false)); - assertThat(indexAliasesService.aliasFilter("cats").toString(), equalTo("QueryWrapperFilter(animal:cat)")); - assertThat(indexAliasesService.aliasFilter("cats", "dogs").toString(), equalTo("QueryWrapperFilter(QueryWrapperFilter(animal:cat) QueryWrapperFilter(animal:dog))")); + assertThat(indexAliasesService.aliasFilter("cats").toString(), equalTo("animal:cat")); + assertThat(indexAliasesService.aliasFilter("cats", "dogs").toString(), equalTo("animal:cat animal:dog")); // Non-filtering alias should turn off all filters because filters are ORed assertThat(indexAliasesService.aliasFilter("all"), nullValue()); assertThat(indexAliasesService.aliasFilter("cats", "all"), nullValue()); assertThat(indexAliasesService.aliasFilter("all", "cats"), nullValue()); - indexAliasesService.add("cats", filter(termFilter("animal", "feline"))); - indexAliasesService.add("dogs", filter(termFilter("animal", "canine"))); - assertThat(indexAliasesService.aliasFilter("dogs", "cats").toString(), equalTo("QueryWrapperFilter(QueryWrapperFilter(animal:canine) QueryWrapperFilter(animal:feline))")); + indexAliasesService.add("cats", filter(termQuery("animal", "feline"))); + indexAliasesService.add("dogs", filter(termQuery("animal", "canine"))); + assertThat(indexAliasesService.aliasFilter("dogs", "cats").toString(), equalTo("animal:canine animal:feline")); } @Test public void testAliasFilters() throws Exception { IndexAliasesService indexAliasesService = newIndexAliasesService(); - indexAliasesService.add("cats", filter(termFilter("animal", "cat"))); - indexAliasesService.add("dogs", filter(termFilter("animal", "dog"))); + indexAliasesService.add("cats", filter(termQuery("animal", "cat"))); + indexAliasesService.add("dogs", filter(termQuery("animal", "dog"))); assertThat(indexAliasesService.aliasFilter(), nullValue()); - assertThat(indexAliasesService.aliasFilter("dogs").toString(), equalTo("QueryWrapperFilter(animal:dog)")); - assertThat(indexAliasesService.aliasFilter("dogs", "cats").toString(), equalTo("QueryWrapperFilter(QueryWrapperFilter(animal:dog) QueryWrapperFilter(animal:cat))")); + assertThat(indexAliasesService.aliasFilter("dogs").toString(), equalTo("animal:dog")); + assertThat(indexAliasesService.aliasFilter("dogs", "cats").toString(), equalTo("animal:dog animal:cat")); - indexAliasesService.add("cats", filter(termFilter("animal", "feline"))); - indexAliasesService.add("dogs", filter(termFilter("animal", "canine"))); + indexAliasesService.add("cats", filter(termQuery("animal", "feline"))); + indexAliasesService.add("dogs", filter(termQuery("animal", "canine"))); - assertThat(indexAliasesService.aliasFilter("dogs", "cats").toString(), equalTo("QueryWrapperFilter(QueryWrapperFilter(animal:canine) QueryWrapperFilter(animal:feline))")); + assertThat(indexAliasesService.aliasFilter("dogs", "cats").toString(), equalTo("animal:canine animal:feline")); } @Test(expected = InvalidAliasNameException.class) public void testRemovedAliasFilter() throws Exception { IndexAliasesService indexAliasesService = newIndexAliasesService(); - indexAliasesService.add("cats", filter(termFilter("animal", "cat"))); + indexAliasesService.add("cats", filter(termQuery("animal", "cat"))); indexAliasesService.remove("cats"); indexAliasesService.aliasFilter("cats"); } @@ -107,8 +107,8 @@ public class IndexAliasesServiceTests extends ElasticsearchSingleNodeTest { @Test public void testUnknownAliasFilter() throws Exception { IndexAliasesService indexAliasesService = newIndexAliasesService(); - indexAliasesService.add("cats", filter(termFilter("animal", "cat"))); - indexAliasesService.add("dogs", filter(termFilter("animal", "dog"))); + indexAliasesService.add("cats", filter(termQuery("animal", "cat"))); + indexAliasesService.add("dogs", filter(termQuery("animal", "dog"))); try { indexAliasesService.aliasFilter("unknown"); diff --git a/src/test/java/org/elasticsearch/index/mapper/date/SimpleDateMappingTests.java b/src/test/java/org/elasticsearch/index/mapper/date/SimpleDateMappingTests.java index 7bb6868241e..3d3a41c79f0 100644 --- a/src/test/java/org/elasticsearch/index/mapper/date/SimpleDateMappingTests.java +++ b/src/test/java/org/elasticsearch/index/mapper/date/SimpleDateMappingTests.java @@ -23,9 +23,7 @@ import org.apache.lucene.analysis.NumericTokenStream.NumericTermAttribute; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.index.DocValuesType; import org.apache.lucene.index.IndexableField; -import org.apache.lucene.search.Filter; import org.apache.lucene.search.NumericRangeQuery; -import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.util.Constants; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; @@ -240,14 +238,13 @@ public class SimpleDateMappingTests extends ElasticsearchSingleNodeTest { .bytes()); assertThat(((LongFieldMapper.CustomLongNumericField) doc.rootDoc().getField("date_field")).numericAsString(), equalTo(Long.toString(new DateTime(TimeValue.timeValueHours(10).millis(), DateTimeZone.UTC).getMillis()))); - Filter filter; + NumericRangeQuery rangeQuery; try { SearchContext.setCurrent(new TestSearchContext()); - filter = defaultMapper.mappers().smartNameFieldMapper("date_field").rangeFilter("10:00:00", "11:00:00", true, true, null); + rangeQuery = (NumericRangeQuery) defaultMapper.mappers().smartNameFieldMapper("date_field").rangeQuery("10:00:00", "11:00:00", true, true, null); } finally { SearchContext.removeCurrent(); } - NumericRangeQuery rangeQuery = (NumericRangeQuery) ((QueryWrapperFilter) filter).getQuery(); assertThat(rangeQuery.getMax(), equalTo(new DateTime(TimeValue.timeValueHours(11).millis()).getMillis())); assertThat(rangeQuery.getMin(), equalTo(new DateTime(TimeValue.timeValueHours(10).millis()).getMillis())); } @@ -267,14 +264,13 @@ public class SimpleDateMappingTests extends ElasticsearchSingleNodeTest { .bytes()); assertThat(((LongFieldMapper.CustomLongNumericField) doc.rootDoc().getField("date_field")).numericAsString(), equalTo(Long.toString(new DateTime(TimeValue.timeValueHours(34).millis(), DateTimeZone.UTC).getMillis()))); - Filter filter; + NumericRangeQuery rangeQuery; try { SearchContext.setCurrent(new TestSearchContext()); - filter = defaultMapper.mappers().smartNameFieldMapper("date_field").rangeFilter("Jan 02 10:00:00", "Jan 02 11:00:00", true, true, null); + rangeQuery = (NumericRangeQuery) defaultMapper.mappers().smartNameFieldMapper("date_field").rangeQuery("Jan 02 10:00:00", "Jan 02 11:00:00", true, true, null); } finally { SearchContext.removeCurrent(); } - NumericRangeQuery rangeQuery = (NumericRangeQuery) ((QueryWrapperFilter) filter).getQuery(); assertThat(rangeQuery.getMax(), equalTo(new DateTime(TimeValue.timeValueHours(35).millis()).getMillis())); assertThat(rangeQuery.getMin(), equalTo(new DateTime(TimeValue.timeValueHours(34).millis()).getMillis())); } diff --git a/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalValuesMapperIntegrationTests.java b/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalValuesMapperIntegrationTests.java index 43c008c81dd..368059456f1 100644 --- a/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalValuesMapperIntegrationTests.java +++ b/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalValuesMapperIntegrationTests.java @@ -25,7 +25,6 @@ import org.elasticsearch.common.geo.builders.ShapeBuilder; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.junit.Test; @@ -66,25 +65,25 @@ public class ExternalValuesMapperIntegrationTests extends ElasticsearchIntegrati SearchResponse response; response = client().prepareSearch("test-idx") - .setPostFilter(FilterBuilders.termFilter("field.bool", "T")) + .setPostFilter(QueryBuilders.termQuery("field.bool", "T")) .execute().actionGet(); assertThat(response.getHits().totalHits(), equalTo((long) 1)); response = client().prepareSearch("test-idx") - .setPostFilter(FilterBuilders.geoDistanceRangeFilter("field.point").point(42.0, 51.0).to("1km")) + .setPostFilter(QueryBuilders.geoDistanceRangeQuery("field.point").point(42.0, 51.0).to("1km")) .execute().actionGet(); assertThat(response.getHits().totalHits(), equalTo((long) 1)); response = client().prepareSearch("test-idx") - .setPostFilter(FilterBuilders.geoShapeFilter("field.shape", ShapeBuilder.newPoint(-100, 45), ShapeRelation.WITHIN)) + .setPostFilter(QueryBuilders.geoShapeQuery("field.shape", ShapeBuilder.newPoint(-100, 45), ShapeRelation.WITHIN)) .execute().actionGet(); assertThat(response.getHits().totalHits(), equalTo((long) 1)); response = client().prepareSearch("test-idx") - .setPostFilter(FilterBuilders.termFilter("field.field", "foo")) + .setPostFilter(QueryBuilders.termQuery("field.field", "foo")) .execute().actionGet(); assertThat(response.getHits().totalHits(), equalTo((long) 1)); diff --git a/src/test/java/org/elasticsearch/index/mapper/multifield/MultiFieldsIntegrationTests.java b/src/test/java/org/elasticsearch/index/mapper/multifield/MultiFieldsIntegrationTests.java index 1808074defa..6b2bd463ca0 100644 --- a/src/test/java/org/elasticsearch/index/mapper/multifield/MultiFieldsIntegrationTests.java +++ b/src/test/java/org/elasticsearch/index/mapper/multifield/MultiFieldsIntegrationTests.java @@ -33,7 +33,7 @@ import org.junit.Test; import java.io.IOException; import java.util.Map; -import static org.elasticsearch.index.query.FilterBuilders.geoDistanceFilter; +import static org.elasticsearch.index.query.QueryBuilders.geoDistanceQuery; import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; @@ -125,7 +125,7 @@ public class MultiFieldsIntegrationTests extends ElasticsearchIntegrationTest { client().prepareIndex("my-index", "my-type", "1").setSource("a", "51,19").setRefresh(true).get(); CountResponse countResponse = client().prepareCount("my-index") - .setQuery(constantScoreQuery(geoDistanceFilter("a").point(51, 19).distance(50, DistanceUnit.KILOMETERS))) + .setQuery(constantScoreQuery(geoDistanceQuery("a").point(51, 19).distance(50, DistanceUnit.KILOMETERS))) .get(); assertThat(countResponse.getCount(), equalTo(1l)); countResponse = client().prepareCount("my-index").setQuery(matchQuery("a.b", "51,19")).get(); diff --git a/src/test/java/org/elasticsearch/index/mapper/string/SimpleStringMappingTests.java b/src/test/java/org/elasticsearch/index/mapper/string/SimpleStringMappingTests.java index f9547fbefe6..bfbc5c963d7 100644 --- a/src/test/java/org/elasticsearch/index/mapper/string/SimpleStringMappingTests.java +++ b/src/test/java/org/elasticsearch/index/mapper/string/SimpleStringMappingTests.java @@ -28,7 +28,6 @@ import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.IndexableFieldType; import org.apache.lucene.index.Term; import org.apache.lucene.queries.TermsQuery; -import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.TermQuery; import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.settings.ImmutableSettings; @@ -41,10 +40,10 @@ import org.elasticsearch.index.IndexService; import org.elasticsearch.index.fielddata.FieldDataType; import org.elasticsearch.index.mapper.ContentPath; import org.elasticsearch.index.mapper.DocumentMapper; -import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.DocumentMapperParser; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.Mapper.BuilderContext; +import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext.Document; import org.elasticsearch.index.mapper.ParsedDocument; import org.elasticsearch.index.mapper.core.StringFieldMapper; @@ -520,7 +519,7 @@ public class SimpleStringMappingTests extends ElasticsearchSingleNodeTest { assertTrue(mergeResult.buildConflicts()[0].contains("cannot enable norms")); } - public void testTermsFilter() throws Exception { + public void testTermsQuery() throws Exception { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field").field("type", "string").field("index", "not_analyzed").endObject().endObject() .endObject().endObject().string(); @@ -529,9 +528,9 @@ public class SimpleStringMappingTests extends ElasticsearchSingleNodeTest { FieldMapper mapper = defaultMapper.mappers().getMapper("field"); assertNotNull(mapper); assertTrue(mapper instanceof StringFieldMapper); - assertEquals(Queries.newMatchNoDocsFilter(), mapper.termsFilter(Collections.emptyList(), null)); - assertEquals(new QueryWrapperFilter(new TermQuery(new Term("field", "value"))), mapper.termsFilter(Collections.singletonList("value"), null)); - assertEquals(new QueryWrapperFilter(new TermsQuery(new Term("field", "value1"), new Term("field", "value2"))), mapper.termsFilter(Arrays.asList("value1", "value2"), null)); + assertEquals(Queries.newMatchNoDocsQuery(), mapper.termsQuery(Collections.emptyList(), null)); + assertEquals(new TermQuery(new Term("field", "value")), mapper.termsQuery(Collections.singletonList("value"), null)); + assertEquals(new TermsQuery(new Term("field", "value1"), new Term("field", "value2")), mapper.termsQuery(Arrays.asList("value1", "value2"), null)); } } diff --git a/src/test/java/org/elasticsearch/index/query/SimpleIndexQueryParserTests.java b/src/test/java/org/elasticsearch/index/query/SimpleIndexQueryParserTests.java index 7eb79ff3ff8..c1095e38554 100644 --- a/src/test/java/org/elasticsearch/index/query/SimpleIndexQueryParserTests.java +++ b/src/test/java/org/elasticsearch/index/query/SimpleIndexQueryParserTests.java @@ -65,7 +65,6 @@ import org.apache.lucene.util.BytesRefBuilder; import org.apache.lucene.util.CharsRefBuilder; import org.apache.lucene.util.NumericUtils; import org.apache.lucene.util.automaton.TooComplexToDeterminizeException; -import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.termvectors.MultiTermVectorsItemResponse; import org.elasticsearch.action.termvectors.MultiTermVectorsRequest; import org.elasticsearch.action.termvectors.MultiTermVectorsResponse; @@ -90,7 +89,6 @@ import org.elasticsearch.index.IndexService; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.ParsedDocument; import org.elasticsearch.index.mapper.core.NumberFieldMapper; -import org.elasticsearch.index.search.NumericRangeFieldDataFilter; import org.elasticsearch.index.search.child.ParentConstantScoreQuery; import org.elasticsearch.index.search.geo.GeoDistanceFilter; import org.elasticsearch.index.search.geo.GeoPolygonFilter; @@ -104,21 +102,14 @@ import org.junit.Test; import java.io.IOException; import java.lang.reflect.Field; +import java.util.Arrays; import java.util.EnumSet; import java.util.List; import static org.elasticsearch.common.io.Streams.copyToBytesFromClasspath; import static org.elasticsearch.common.io.Streams.copyToStringFromClasspath; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.andFilter; -import static org.elasticsearch.index.query.FilterBuilders.boolFilter; -import static org.elasticsearch.index.query.FilterBuilders.notFilter; -import static org.elasticsearch.index.query.FilterBuilders.orFilter; -import static org.elasticsearch.index.query.FilterBuilders.prefixFilter; -import static org.elasticsearch.index.query.FilterBuilders.queryFilter; -import static org.elasticsearch.index.query.FilterBuilders.rangeFilter; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; -import static org.elasticsearch.index.query.FilterBuilders.termsFilter; +import static org.elasticsearch.index.query.QueryBuilders.andQuery; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.boostingQuery; import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; @@ -128,6 +119,8 @@ import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.fuzzyQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.moreLikeThisQuery; +import static org.elasticsearch.index.query.QueryBuilders.notQuery; +import static org.elasticsearch.index.query.QueryBuilders.orQuery; import static org.elasticsearch.index.query.QueryBuilders.prefixQuery; import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; @@ -141,6 +134,7 @@ import static org.elasticsearch.index.query.QueryBuilders.spanTermQuery; import static org.elasticsearch.index.query.QueryBuilders.spanWithinQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.index.query.QueryBuilders.termsQuery; +import static org.elasticsearch.index.query.QueryBuilders.termsQuery; import static org.elasticsearch.index.query.QueryBuilders.wildcardQuery; import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.factorFunction; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBooleanSubQuery; @@ -602,7 +596,7 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { @Test public void testPrefiFilteredQueryBuilder() throws IOException { IndexQueryParserService queryParser = queryParser(); - Query parsedQuery = queryParser.parse(filteredQuery(termQuery("name.first", "shay"), prefixFilter("name.first", "sh"))).query(); + Query parsedQuery = queryParser.parse(filteredQuery(termQuery("name.first", "shay"), prefixQuery("name.first", "sh"))).query(); assertThat(parsedQuery, instanceOf(FilteredQuery.class)); FilteredQuery filteredQuery = (FilteredQuery) parsedQuery; QueryWrapperFilter filter = (QueryWrapperFilter) filteredQuery.getFilter(); @@ -631,8 +625,8 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { assertThat(parsedQuery.query(), instanceOf(FilteredQuery.class)); FilteredQuery filteredQuery = (FilteredQuery) parsedQuery.query(); QueryWrapperFilter filter = (QueryWrapperFilter) filteredQuery.getFilter(); - PrefixQuery prefixFilter = (PrefixQuery) filter.getQuery(); - assertThat(prefixFilter.getPrefix(), equalTo(new Term("name.first", "sh"))); + PrefixQuery prefixQuery = (PrefixQuery) filter.getQuery(); + assertThat(prefixQuery.getPrefix(), equalTo(new Term("name.first", "sh"))); } @Test @@ -857,7 +851,7 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { @Test public void testRangeFilteredQueryBuilder() throws IOException { IndexQueryParserService queryParser = queryParser(); - Query parsedQuery = queryParser.parse(filteredQuery(termQuery("name.first", "shay"), rangeFilter("age").from(23).to(54).includeLower(true).includeUpper(false))).query(); + Query parsedQuery = queryParser.parse(filteredQuery(termQuery("name.first", "shay"), rangeQuery("age").from(23).to(54).includeLower(true).includeUpper(false))).query(); FilteredQuery expected = new FilteredQuery( new TermQuery(new Term("name.first", "shay")), new QueryWrapperFilter(NumericRangeQuery.newLongRange("age", 23L, 54L, true, false))); @@ -886,31 +880,16 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { assertEquals(expected, parsedQuery); } - @Test - public void testRangeFilteredQueryBuilder_executionFieldData() throws IOException { - IndexQueryParserService queryParser = queryParser(); - Query parsedQuery = queryParser.parse(filteredQuery(termQuery("name.first", "shay"), rangeFilter("age").from(23).to(54).includeLower(true).includeUpper(false).setExecution("fielddata"))).query(); - assertThat(parsedQuery, instanceOf(FilteredQuery.class)); - Filter filter = ((FilteredQuery) parsedQuery).getFilter(); - assertThat(filter, instanceOf(NumericRangeFieldDataFilter.class)); - NumericRangeFieldDataFilter rangeFilter = (NumericRangeFieldDataFilter) filter; - assertThat(rangeFilter.getField(), equalTo("age")); - assertThat(rangeFilter.getLowerVal().intValue(), equalTo(23)); - assertThat(rangeFilter.getUpperVal().intValue(), equalTo(54)); - assertThat(rangeFilter.isIncludeLower(), equalTo(true)); - assertThat(rangeFilter.isIncludeUpper(), equalTo(false)); - } - @Test public void testBoolFilteredQueryBuilder() throws IOException { IndexQueryParserService queryParser = queryParser(); - Query parsedQuery = queryParser.parse(filteredQuery(termQuery("name.first", "shay"), boolFilter().must(termFilter("name.first", "shay1"), termFilter("name.first", "shay4")).mustNot(termFilter("name.first", "shay2")).should(termFilter("name.first", "shay3")))).query(); + Query parsedQuery = queryParser.parse(filteredQuery(termQuery("name.first", "shay"), boolQuery().must(termQuery("name.first", "shay1")).must(termQuery("name.first", "shay4")).mustNot(termQuery("name.first", "shay2")).should(termQuery("name.first", "shay3")))).query(); BooleanQuery filter = new BooleanQuery(); - filter.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay1"))), Occur.MUST); - filter.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay4"))), Occur.MUST); - filter.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay2"))), Occur.MUST_NOT); - filter.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay3"))), Occur.SHOULD); + filter.add(new TermQuery(new Term("name.first", "shay1")), Occur.MUST); + filter.add(new TermQuery(new Term("name.first", "shay4")), Occur.MUST); + filter.add(new TermQuery(new Term("name.first", "shay2")), Occur.MUST_NOT); + filter.add(new TermQuery(new Term("name.first", "shay3")), Occur.SHOULD); filter.setMinimumNumberShouldMatch(1); FilteredQuery expected = new FilteredQuery( new TermQuery(new Term("name.first", "shay")), @@ -925,10 +904,10 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { String query = copyToStringFromClasspath("/org/elasticsearch/index/query/bool-filter.json"); Query parsedQuery = queryParser.parse(query).query(); BooleanQuery filter = new BooleanQuery(); - filter.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay1"))), Occur.MUST); - filter.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay4"))), Occur.MUST); - filter.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay2"))), Occur.MUST_NOT); - filter.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay3"))), Occur.SHOULD); + filter.add(new TermQuery(new Term("name.first", "shay1")), Occur.MUST); + filter.add(new TermQuery(new Term("name.first", "shay4")), Occur.MUST); + filter.add(new TermQuery(new Term("name.first", "shay2")), Occur.MUST_NOT); + filter.add(new TermQuery(new Term("name.first", "shay3")), Occur.SHOULD); filter.setMinimumNumberShouldMatch(1); FilteredQuery expected = new FilteredQuery( new TermQuery(new Term("name.first", "shay")), @@ -939,11 +918,11 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { @Test public void testAndFilteredQueryBuilder() throws IOException { IndexQueryParserService queryParser = queryParser(); - Query parsedQuery = queryParser.parse(filteredQuery(matchAllQuery(), andFilter(termFilter("name.first", "shay1"), termFilter("name.first", "shay4")))).query(); + Query parsedQuery = queryParser.parse(filteredQuery(matchAllQuery(), andQuery(termQuery("name.first", "shay1"), termQuery("name.first", "shay4")))).query(); BooleanQuery and = new BooleanQuery(); - and.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay1"))), Occur.MUST); - and.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay4"))), Occur.MUST); - ConstantScoreQuery expected = new ConstantScoreQuery(new QueryWrapperFilter(and)); + and.add(new TermQuery(new Term("name.first", "shay1")), Occur.MUST); + and.add(new TermQuery(new Term("name.first", "shay4")), Occur.MUST); + ConstantScoreQuery expected = new ConstantScoreQuery(and); assertEquals(expected, parsedQuery); } @@ -953,8 +932,8 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { String query = copyToStringFromClasspath("/org/elasticsearch/index/query/and-filter.json"); Query parsedQuery = queryParser.parse(query).query(); BooleanQuery and = new BooleanQuery(); - and.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay1"))), Occur.MUST); - and.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay4"))), Occur.MUST); + and.add(new TermQuery(new Term("name.first", "shay1")), Occur.MUST); + and.add(new TermQuery(new Term("name.first", "shay4")), Occur.MUST); FilteredQuery expected = new FilteredQuery( new TermQuery(new Term("name.first", "shay")), new QueryWrapperFilter(and)); @@ -967,8 +946,8 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { String query = copyToStringFromClasspath("/org/elasticsearch/index/query/and-filter-named.json"); Query parsedQuery = queryParser.parse(query).query(); BooleanQuery and = new BooleanQuery(); - and.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay1"))), Occur.MUST); - and.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay4"))), Occur.MUST); + and.add(new TermQuery(new Term("name.first", "shay1")), Occur.MUST); + and.add(new TermQuery(new Term("name.first", "shay4")), Occur.MUST); FilteredQuery expected = new FilteredQuery( new TermQuery(new Term("name.first", "shay")), new QueryWrapperFilter(and)); @@ -981,8 +960,8 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { String query = copyToStringFromClasspath("/org/elasticsearch/index/query/and-filter2.json"); Query parsedQuery = queryParser.parse(query).query(); BooleanQuery and = new BooleanQuery(); - and.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay1"))), Occur.MUST); - and.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay4"))), Occur.MUST); + and.add(new TermQuery(new Term("name.first", "shay1")), Occur.MUST); + and.add(new TermQuery(new Term("name.first", "shay4")), Occur.MUST); FilteredQuery expected = new FilteredQuery( new TermQuery(new Term("name.first", "shay")), new QueryWrapperFilter(and)); @@ -992,11 +971,11 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { @Test public void testOrFilteredQueryBuilder() throws IOException { IndexQueryParserService queryParser = queryParser(); - Query parsedQuery = queryParser.parse(filteredQuery(matchAllQuery(), orFilter(termFilter("name.first", "shay1"), termFilter("name.first", "shay4")))).query(); + Query parsedQuery = queryParser.parse(filteredQuery(matchAllQuery(), orQuery(termQuery("name.first", "shay1"), termQuery("name.first", "shay4")))).query(); BooleanQuery or = new BooleanQuery(); - or.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay1"))), Occur.SHOULD); - or.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay4"))), Occur.SHOULD); - ConstantScoreQuery expected = new ConstantScoreQuery(new QueryWrapperFilter(or)); + or.add(new TermQuery(new Term("name.first", "shay1")), Occur.SHOULD); + or.add(new TermQuery(new Term("name.first", "shay4")), Occur.SHOULD); + ConstantScoreQuery expected = new ConstantScoreQuery(or); assertEquals(expected, parsedQuery); } @@ -1006,8 +985,8 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { String query = copyToStringFromClasspath("/org/elasticsearch/index/query/or-filter.json"); Query parsedQuery = queryParser.parse(query).query(); BooleanQuery or = new BooleanQuery(); - or.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay1"))), Occur.SHOULD); - or.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay4"))), Occur.SHOULD); + or.add(new TermQuery(new Term("name.first", "shay1")), Occur.SHOULD); + or.add(new TermQuery(new Term("name.first", "shay4")), Occur.SHOULD); FilteredQuery expected = new FilteredQuery( new TermQuery(new Term("name.first", "shay")), new QueryWrapperFilter(or)); @@ -1020,8 +999,8 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { String query = copyToStringFromClasspath("/org/elasticsearch/index/query/or-filter2.json"); Query parsedQuery = queryParser.parse(query).query(); BooleanQuery or = new BooleanQuery(); - or.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay1"))), Occur.SHOULD); - or.add(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay4"))), Occur.SHOULD); + or.add(new TermQuery(new Term("name.first", "shay1")), Occur.SHOULD); + or.add(new TermQuery(new Term("name.first", "shay4")), Occur.SHOULD); FilteredQuery expected = new FilteredQuery( new TermQuery(new Term("name.first", "shay")), new QueryWrapperFilter(or)); @@ -1031,8 +1010,8 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { @Test public void testNotFilteredQueryBuilder() throws IOException { IndexQueryParserService queryParser = queryParser(); - Query parsedQuery = queryParser.parse(filteredQuery(matchAllQuery(), notFilter(termFilter("name.first", "shay1")))).query(); - ConstantScoreQuery expected = new ConstantScoreQuery(new QueryWrapperFilter(Queries.not(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay1")))))); + Query parsedQuery = queryParser.parse(filteredQuery(matchAllQuery(), notQuery(termQuery("name.first", "shay1")))).query(); + ConstantScoreQuery expected = new ConstantScoreQuery(Queries.not(new TermQuery(new Term("name.first", "shay1")))); assertEquals(expected, parsedQuery); } @@ -1044,7 +1023,7 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { assertThat(parsedQuery, instanceOf(FilteredQuery.class)); FilteredQuery expected = new FilteredQuery( new TermQuery(new Term("name.first", "shay")), - new QueryWrapperFilter(Queries.not(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay1")))))); + new QueryWrapperFilter(Queries.not(new TermQuery(new Term("name.first", "shay1"))))); assertEquals(expected, parsedQuery); } @@ -1055,7 +1034,7 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { Query parsedQuery = queryParser.parse(query).query(); FilteredQuery expected = new FilteredQuery( new TermQuery(new Term("name.first", "shay")), - new QueryWrapperFilter(Queries.not(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay1")))))); + new QueryWrapperFilter(Queries.not(new TermQuery(new Term("name.first", "shay1"))))); assertEquals(expected, parsedQuery); } @@ -1066,7 +1045,7 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { Query parsedQuery = queryParser.parse(query).query(); FilteredQuery expected = new FilteredQuery( new TermQuery(new Term("name.first", "shay")), - new QueryWrapperFilter(Queries.not(new QueryWrapperFilter(new TermQuery(new Term("name.first", "shay1")))))); + new QueryWrapperFilter(Queries.not(new TermQuery(new Term("name.first", "shay1"))))); assertEquals(expected, parsedQuery); } @@ -1205,7 +1184,7 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { queryParser.parse(query).query(); fail(); } catch (QueryParsingException ex) { - assertThat(ex.getMessage(), equalTo("[terms] filter does not support multiple fields")); + assertThat(ex.getMessage(), equalTo("[terms] query does not support multiple fields")); } } @@ -1234,7 +1213,7 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { @Test public void testFilteredQueryBuilder() throws IOException { IndexQueryParserService queryParser = queryParser(); - Query parsedQuery = queryParser.parse(filteredQuery(termQuery("name.first", "shay"), termFilter("name.last", "banon"))).query(); + Query parsedQuery = queryParser.parse(filteredQuery(termQuery("name.first", "shay"), termQuery("name.last", "banon"))).query(); assertThat(parsedQuery, instanceOf(FilteredQuery.class)); FilteredQuery filteredQuery = (FilteredQuery) parsedQuery; assertThat(((TermQuery) filteredQuery.getQuery()).getTerm(), equalTo(new Term("name.first", "shay"))); @@ -1301,9 +1280,9 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { assertThat(parsedQuery, instanceOf(FilteredQuery.class)); FilteredQuery filteredQuery = (FilteredQuery) parsedQuery; QueryWrapperFilter filter = (QueryWrapperFilter) filteredQuery.getFilter(); - TermQuery termFilter = (TermQuery) filter.getQuery(); - assertThat(termFilter.getTerm().field(), equalTo("name.last")); - assertThat(termFilter.getTerm().text(), equalTo("banon")); + TermQuery termQuery = (TermQuery) filter.getQuery(); + assertThat(termQuery.getTerm().field(), equalTo("name.last")); + assertThat(termQuery.getTerm().text(), equalTo("banon")); } @Test @@ -1315,15 +1294,15 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { assertThat(parsedQuery.query(), instanceOf(FilteredQuery.class)); FilteredQuery filteredQuery = (FilteredQuery) parsedQuery.query(); QueryWrapperFilter filter = (QueryWrapperFilter) filteredQuery.getFilter(); - TermQuery termFilter = (TermQuery) filter.getQuery(); - assertThat(termFilter.getTerm().field(), equalTo("name.last")); - assertThat(termFilter.getTerm().text(), equalTo("banon")); + TermQuery termQuery = (TermQuery) filter.getQuery(); + assertThat(termQuery.getTerm().field(), equalTo("name.last")); + assertThat(termQuery.getTerm().text(), equalTo("banon")); } @Test public void testTermsFilterQueryBuilder() throws Exception { IndexQueryParserService queryParser = queryParser(); - Query parsedQuery = queryParser.parse(filteredQuery(termQuery("name.first", "shay"), termsFilter("name.last", "banon", "kimchy"))).query(); + Query parsedQuery = queryParser.parse(filteredQuery(termQuery("name.first", "shay"), termsQuery("name.last", "banon", "kimchy"))).query(); assertThat(parsedQuery, instanceOf(FilteredQuery.class)); FilteredQuery filteredQuery = (FilteredQuery) parsedQuery; QueryWrapperFilter filter = (QueryWrapperFilter) filteredQuery.getFilter(); @@ -1357,7 +1336,7 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { @Test public void testConstantScoreQueryBuilder() throws IOException { IndexQueryParserService queryParser = queryParser(); - Query parsedQuery = queryParser.parse(constantScoreQuery(termFilter("name.last", "banon"))).query(); + Query parsedQuery = queryParser.parse(constantScoreQuery(termQuery("name.last", "banon"))).query(); assertThat(parsedQuery, instanceOf(ConstantScoreQuery.class)); ConstantScoreQuery constantScoreQuery = (ConstantScoreQuery) parsedQuery; assertThat(getTerm(constantScoreQuery.getQuery()), equalTo(new Term("name.last", "banon"))); @@ -1655,9 +1634,9 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { } @Test - public void testQueryFilterBuilder() throws Exception { + public void testQueryQueryBuilder() throws Exception { IndexQueryParserService queryParser = queryParser(); - Query parsedQuery = queryParser.parse(filteredQuery(termQuery("name.first", "shay"), queryFilter(termQuery("name.last", "banon")))).query(); + Query parsedQuery = queryParser.parse(filteredQuery(termQuery("name.first", "shay"), termQuery("name.last", "banon"))).query(); assertThat(parsedQuery, instanceOf(FilteredQuery.class)); FilteredQuery filteredQuery = (FilteredQuery) parsedQuery; QueryWrapperFilter queryWrapperFilter = (QueryWrapperFilter) filteredQuery.getFilter(); @@ -1676,11 +1655,7 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { assertThat(parsedQuery, instanceOf(FilteredQuery.class)); FilteredQuery filteredQuery = (FilteredQuery) parsedQuery; QueryWrapperFilter queryWrapperFilter = (QueryWrapperFilter) filteredQuery.getFilter(); - Field field = QueryWrapperFilter.class.getDeclaredField("query"); - field.setAccessible(true); - Query wrappedQuery = (Query) field.get(queryWrapperFilter); - assertThat(wrappedQuery, instanceOf(TermQuery.class)); - assertThat(((TermQuery) wrappedQuery).getTerm(), equalTo(new Term("name.last", "banon"))); + assertEquals(new ConstantScoreQuery(new TermQuery(new Term("name.last", "banon"))), queryWrapperFilter.getQuery()); } @Test @@ -1692,11 +1667,8 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { assertThat(parsedQuery.query(), instanceOf(FilteredQuery.class)); FilteredQuery filteredQuery = (FilteredQuery) parsedQuery.query(); QueryWrapperFilter queryWrapperFilter = (QueryWrapperFilter) filteredQuery.getFilter(); - Field field = QueryWrapperFilter.class.getDeclaredField("query"); - field.setAccessible(true); - Query wrappedQuery = (Query) field.get(queryWrapperFilter); - assertThat(wrappedQuery, instanceOf(TermQuery.class)); - assertThat(((TermQuery) wrappedQuery).getTerm(), equalTo(new Term("name.last", "banon"))); + Query wrappedQuery = queryWrapperFilter.getQuery(); + assertEquals(new ConstantScoreQuery(new TermQuery(new Term("name.last", "banon"))), wrappedQuery); } @Test @@ -2241,8 +2213,10 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { String query = copyToStringFromClasspath("/org/elasticsearch/index/query/geoShape-filter.json"); Query parsedQuery = queryParser.parse(query).query(); assertThat(parsedQuery, instanceOf(ConstantScoreQuery.class)); - ConstantScoreQuery constantScoreQuery = (ConstantScoreQuery) parsedQuery; - assertThat(constantScoreQuery.getQuery(), instanceOf(IntersectsPrefixTreeFilter.class)); + while (parsedQuery instanceof ConstantScoreQuery) { + parsedQuery = ((ConstantScoreQuery) parsedQuery).getQuery(); + } + assertThat(parsedQuery, instanceOf(IntersectsPrefixTreeFilter.class)); } @Test @@ -2390,14 +2364,8 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { IndexQueryParserService queryParser = queryParser(); String query = copyToStringFromClasspath("/org/elasticsearch/index/query/fquery-with-empty-bool-query.json"); XContentParser parser = XContentHelper.createParser(new BytesArray(query)); - ParsedFilter parsedQuery = queryParser.parseInnerFilter(parser); - assertThat(parsedQuery.filter(), instanceOf(QueryWrapperFilter.class)); - //QueryWrapperFilter filter = parsedQuery.filter(); - assertThat(((QueryWrapperFilter) parsedQuery.filter()).getQuery(), instanceOf(FilteredQuery.class)); - QueryWrapperFilter inner = (QueryWrapperFilter) ((FilteredQuery) ((QueryWrapperFilter) parsedQuery.filter()).getQuery()).getFilter(); - assertThat(inner.getQuery(), instanceOf(TermQuery.class)); - TermQuery filter = (TermQuery) inner.getQuery(); - assertThat(filter.getTerm().toString(), equalTo("text:apache")); + ParsedQuery parsedQuery = queryParser.parseInnerFilter(parser); + assertEquals(new ConstantScoreQuery(new FilteredQuery(new TermQuery(new Term("text", "apache")), new QueryWrapperFilter(new TermQuery(new Term("text", "apache"))))), parsedQuery.query()); } @Test @@ -2496,9 +2464,8 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { IndexQueryParserService queryParser = indexService.queryParserService(); Query parsedQuery = queryParser.parse(query).query(); assertThat(parsedQuery, instanceOf(ConstantScoreQuery.class)); - assertThat(((ConstantScoreQuery) parsedQuery).getQuery(), instanceOf(QueryWrapperFilter.class)); - assertThat(((QueryWrapperFilter) ((ConstantScoreQuery) parsedQuery).getQuery()).getQuery(), instanceOf(ParentConstantScoreQuery.class)); - assertThat(((QueryWrapperFilter) ((ConstantScoreQuery) parsedQuery).getQuery()).getQuery().toString(), equalTo("parent_filter[foo](filtered(*:*)->QueryWrapperFilter(_type:foo))")); + assertThat(((ConstantScoreQuery) parsedQuery).getQuery(), instanceOf(ParentConstantScoreQuery.class)); + assertThat(((ConstantScoreQuery) parsedQuery).getQuery().toString(), equalTo("parent_filter[foo](+*:* #ConstantScore(_type:foo))")); SearchContext.removeCurrent(); } @@ -2511,4 +2478,35 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest { TermQuery wrapped = (TermQuery) query; return wrapped.getTerm(); } + + public void testDefaultBooleanQueryMinShouldMatch() throws Exception { + IndexQueryParserService queryParser = queryParser(); + + // Queries have a minShouldMatch of 0 + BooleanQuery bq = (BooleanQuery) queryParser.parse(boolQuery().must(termQuery("foo", "bar"))).query(); + assertEquals(0, bq.getMinimumNumberShouldMatch()); + + bq = (BooleanQuery) queryParser.parse(boolQuery().should(termQuery("foo", "bar"))).query(); + assertEquals(0, bq.getMinimumNumberShouldMatch()); + + // Filters have a minShouldMatch of 0/1 + ConstantScoreQuery csq = (ConstantScoreQuery) queryParser.parse(constantScoreQuery(boolQuery().must(termQuery("foo", "bar")))).query(); + bq = (BooleanQuery) csq.getQuery(); + assertEquals(0, bq.getMinimumNumberShouldMatch()); + + csq = (ConstantScoreQuery) queryParser.parse(constantScoreQuery(boolQuery().should(termQuery("foo", "bar")))).query(); + bq = (BooleanQuery) csq.getQuery(); + assertEquals(1, bq.getMinimumNumberShouldMatch()); + } + + public void testTermsQueryFilter() throws Exception { + // TermsQuery is tricky in that it parses differently as a query or a filter + IndexQueryParserService queryParser = queryParser(); + Query q = queryParser.parse(termsQuery("foo", Arrays.asList("bar"))).query(); + assertThat(q, instanceOf(BooleanQuery.class)); + + ConstantScoreQuery csq = (ConstantScoreQuery) queryParser.parse(constantScoreQuery(termsQuery("foo", Arrays.asList("bar")))).query(); + q = csq.getQuery(); + assertThat(q, instanceOf(TermsQuery.class)); + } } diff --git a/src/test/java/org/elasticsearch/index/query/guice/IndexQueryParserModuleTests.java b/src/test/java/org/elasticsearch/index/query/guice/IndexQueryParserModuleTests.java index d6d792400c4..4f218ed29bc 100644 --- a/src/test/java/org/elasticsearch/index/query/guice/IndexQueryParserModuleTests.java +++ b/src/test/java/org/elasticsearch/index/query/guice/IndexQueryParserModuleTests.java @@ -37,8 +37,6 @@ public class IndexQueryParserModuleTests extends ElasticsearchSingleNodeTest { Settings settings = settingsBuilder() .put("index.queryparser.query.my.type", MyJsonQueryParser.class) .put("index.queryparser.query.my.param1", "value1") - .put("index.queryparser.filter.my.type", MyJsonFilterParser.class) - .put("index.queryparser.filter.my.param2", "value2") .put("index.cache.filter.type", "none") .put("name", "IndexQueryParserModuleTests") .build(); @@ -49,9 +47,5 @@ public class IndexQueryParserModuleTests extends ElasticsearchSingleNodeTest { assertThat(myJsonQueryParser.names()[0], equalTo("my")); assertThat(myJsonQueryParser.settings().get("param1"), equalTo("value1")); - - MyJsonFilterParser myJsonFilterParser = (MyJsonFilterParser) indexQueryParserService.filterParser("my"); - assertThat(myJsonFilterParser.names()[0], equalTo("my")); - assertThat(myJsonFilterParser.settings().get("param2"), equalTo("value2")); } } diff --git a/src/test/java/org/elasticsearch/index/query/guice/MyJsonFilterParser.java b/src/test/java/org/elasticsearch/index/query/guice/MyJsonFilterParser.java deleted file mode 100644 index 09b53d32ba4..00000000000 --- a/src/test/java/org/elasticsearch/index/query/guice/MyJsonFilterParser.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query.guice; - -import org.apache.lucene.search.Filter; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.inject.assistedinject.Assisted; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.index.AbstractIndexComponent; -import org.elasticsearch.index.Index; -import org.elasticsearch.index.query.FilterParser; -import org.elasticsearch.index.query.QueryParseContext; -import org.elasticsearch.index.query.QueryParsingException; -import org.elasticsearch.index.settings.IndexSettings; - -import java.io.IOException; - -/** - * - */ -public class MyJsonFilterParser extends AbstractIndexComponent implements FilterParser { - - private final String name; - - private final Settings settings; - - @Inject - public MyJsonFilterParser(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) { - super(index, indexSettings); - this.name = name; - this.settings = settings; - } - - @Override - public String[] names() { - return new String[]{this.name}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - return null; - } - - public Settings settings() { - return settings; - } -} \ No newline at end of file diff --git a/src/test/java/org/elasticsearch/index/query/plugin/IndexQueryParserPlugin2Tests.java b/src/test/java/org/elasticsearch/index/query/plugin/IndexQueryParserPlugin2Tests.java index a7d30c465dd..0173aee722e 100644 --- a/src/test/java/org/elasticsearch/index/query/plugin/IndexQueryParserPlugin2Tests.java +++ b/src/test/java/org/elasticsearch/index/query/plugin/IndexQueryParserPlugin2Tests.java @@ -65,7 +65,6 @@ public class IndexQueryParserPlugin2Tests extends ElasticsearchTestCase { IndexQueryParserModule queryParserModule = new IndexQueryParserModule(settings); queryParserModule.addQueryParser("my", PluginJsonQueryParser.class); - queryParserModule.addFilterParser("my", PluginJsonFilterParser.class); Index index = new Index("test"); Injector injector = new ModulesBuilder().add( @@ -96,9 +95,6 @@ public class IndexQueryParserPlugin2Tests extends ElasticsearchTestCase { assertThat(myJsonQueryParser.names()[0], equalTo("my")); - PluginJsonFilterParser myJsonFilterParser = (PluginJsonFilterParser) indexQueryParserService.filterParser("my"); - assertThat(myJsonFilterParser.names()[0], equalTo("my")); - terminate(injector.getInstance(ThreadPool.class)); } } diff --git a/src/test/java/org/elasticsearch/index/query/plugin/IndexQueryParserPluginTests.java b/src/test/java/org/elasticsearch/index/query/plugin/IndexQueryParserPluginTests.java index bbbee452284..16cc4dda535 100644 --- a/src/test/java/org/elasticsearch/index/query/plugin/IndexQueryParserPluginTests.java +++ b/src/test/java/org/elasticsearch/index/query/plugin/IndexQueryParserPluginTests.java @@ -69,11 +69,6 @@ public class IndexQueryParserPluginTests extends ElasticsearchTestCase { public void processXContentQueryParsers(XContentQueryParsersBindings bindings) { bindings.processXContentQueryParser("my", PluginJsonQueryParser.class); } - - @Override - public void processXContentFilterParsers(XContentFilterParsersBindings bindings) { - bindings.processXContentQueryFilter("my", PluginJsonFilterParser.class); - } }); Index index = new Index("test"); @@ -105,9 +100,6 @@ public class IndexQueryParserPluginTests extends ElasticsearchTestCase { assertThat(myJsonQueryParser.names()[0], equalTo("my")); - PluginJsonFilterParser myJsonFilterParser = (PluginJsonFilterParser) indexQueryParserService.filterParser("my"); - assertThat(myJsonFilterParser.names()[0], equalTo("my")); - terminate(injector.getInstance(ThreadPool.class)); } } diff --git a/src/test/java/org/elasticsearch/index/query/plugin/PluginJsonFilterParser.java b/src/test/java/org/elasticsearch/index/query/plugin/PluginJsonFilterParser.java deleted file mode 100644 index 194060e709c..00000000000 --- a/src/test/java/org/elasticsearch/index/query/plugin/PluginJsonFilterParser.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query.plugin; - -import org.apache.lucene.search.Filter; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.inject.assistedinject.Assisted; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.index.AbstractIndexComponent; -import org.elasticsearch.index.Index; -import org.elasticsearch.index.query.FilterParser; -import org.elasticsearch.index.query.QueryParseContext; -import org.elasticsearch.index.query.QueryParsingException; -import org.elasticsearch.index.settings.IndexSettings; - -import java.io.IOException; - -/** - * - */ -public class PluginJsonFilterParser extends AbstractIndexComponent implements FilterParser { - - private final String name; - - private final Settings settings; - - @Inject - public PluginJsonFilterParser(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) { - super(index, indexSettings); - this.name = name; - this.settings = settings; - } - - @Override - public String[] names() { - return new String[]{this.name}; - } - - @Override - public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - return null; - } - - public Settings settings() { - return settings; - } -} \ No newline at end of file diff --git a/src/test/java/org/elasticsearch/index/query/regexp-max-determinized-states.json b/src/test/java/org/elasticsearch/index/query/regexp-max-determinized-states.json index d595bb48c4d..df2f5cc6030 100644 --- a/src/test/java/org/elasticsearch/index/query/regexp-max-determinized-states.json +++ b/src/test/java/org/elasticsearch/index/query/regexp-max-determinized-states.json @@ -1,6 +1,8 @@ { "regexp": { - "name.first": "s.*y", - "max_determinized_states": 5000 + "name.first": { + "value": "s.*y", + "max_determinized_states": 5000 + } } } diff --git a/src/test/java/org/elasticsearch/index/search/FieldDataTermsFilterTests.java b/src/test/java/org/elasticsearch/index/search/FieldDataTermsFilterTests.java deleted file mode 100644 index 7f8ddb89656..00000000000 --- a/src/test/java/org/elasticsearch/index/search/FieldDataTermsFilterTests.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.search; - -import com.carrotsearch.hppc.DoubleOpenHashSet; -import com.carrotsearch.hppc.LongOpenHashSet; -import com.carrotsearch.hppc.ObjectOpenHashSet; -import org.apache.lucene.analysis.standard.StandardAnalyzer; -import org.apache.lucene.document.*; -import org.apache.lucene.index.*; -import org.apache.lucene.store.RAMDirectory; -import org.apache.lucene.util.BytesRef; -import org.apache.lucene.util.FixedBitSet; -import org.elasticsearch.common.settings.ImmutableSettings; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.index.fielddata.IndexFieldData; -import org.elasticsearch.index.fielddata.IndexFieldDataService; -import org.elasticsearch.index.fielddata.IndexNumericFieldData; -import org.elasticsearch.index.mapper.ContentPath; -import org.elasticsearch.index.mapper.FieldMapper; -import org.elasticsearch.index.mapper.Mapper; -import org.elasticsearch.index.mapper.core.DoubleFieldMapper; -import org.elasticsearch.index.mapper.core.LongFieldMapper; -import org.elasticsearch.index.mapper.core.NumberFieldMapper; -import org.elasticsearch.index.mapper.core.StringFieldMapper; -import org.elasticsearch.index.query.IndexQueryParserService; -import org.elasticsearch.index.query.QueryParseContext; -import org.elasticsearch.index.IndexService; -import org.elasticsearch.search.internal.SearchContext; -import org.elasticsearch.test.ElasticsearchSingleNodeTest; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.hamcrest.CoreMatchers.equalTo; - -/** - */ -public class FieldDataTermsFilterTests extends ElasticsearchSingleNodeTest { - - protected QueryParseContext parseContext; - protected IndexFieldDataService ifdService; - protected IndexWriter writer; - protected LeafReader reader; - protected StringFieldMapper strMapper; - protected LongFieldMapper lngMapper; - protected DoubleFieldMapper dblMapper; - - @Before - public void setup() throws Exception { - super.setUp(); - - // create index and fielddata service - IndexService indexService = createIndex("test", ImmutableSettings.builder().put("index.fielddata.cache", "none").build()); - Settings settings = indexService.settingsService().getSettings(); - ifdService = indexService.injector().getInstance(IndexFieldDataService.class); - IndexQueryParserService parserService = indexService.queryParserService(); - parseContext = new QueryParseContext(indexService.index(), parserService); - writer = new IndexWriter(new RAMDirectory(), - new IndexWriterConfig(new StandardAnalyzer())); - - // setup field mappers - strMapper = new StringFieldMapper.Builder("str_value").docValues(false) - .build(new Mapper.BuilderContext(settings, new ContentPath(1))); - - lngMapper = new LongFieldMapper.Builder("lng_value").docValues(false) - .build(new Mapper.BuilderContext(settings, new ContentPath(1))); - - dblMapper = new DoubleFieldMapper.Builder("dbl_value").docValues(false) - .build(new Mapper.BuilderContext(settings, new ContentPath(1))); - - int numDocs = 10; - for (int i = 0; i < numDocs; i++) { - Document d = new Document(); - d.add(new StringField(strMapper.names().indexName(), "str" + i, Field.Store.NO)); - d.add(new LongField(lngMapper.names().indexName(), i, Field.Store.NO)); - d.add(new DoubleField(dblMapper.names().indexName(), Double.valueOf(i), Field.Store.NO)); - writer.addDocument(d); - } - - reader = SlowCompositeReaderWrapper.wrap(DirectoryReader.open(writer, true)); - } - - @Override - @After - public void tearDown() throws Exception { - super.tearDown(); - reader.close(); - writer.close(); - ifdService.clear(); - SearchContext.removeCurrent(); - } - - protected IFD getFieldData(FieldMapper fieldMapper) { - return ifdService.getForField(fieldMapper); - } - - protected IFD getFieldData(NumberFieldMapper fieldMapper) { - return ifdService.getForField(fieldMapper); - } - - @Test - public void testBytes() throws Exception { - List docs = Arrays.asList(1, 5, 7); - - ObjectOpenHashSet hTerms = new ObjectOpenHashSet<>(); - List cTerms = new ArrayList<>(docs.size()); - for (int i = 0; i < docs.size(); i++) { - BytesRef term = new BytesRef("str" + docs.get(i)); - hTerms.add(term); - cTerms.add(term); - } - - FieldDataTermsFilter hFilter = FieldDataTermsFilter.newBytes(getFieldData(strMapper), hTerms); - - int size = reader.maxDoc(); - FixedBitSet result = new FixedBitSet(size); - - result.clear(0, size); - assertThat(result.cardinality(), equalTo(0)); - result.or(hFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); - assertThat(result.cardinality(), equalTo(docs.size())); - for (int i = 0; i < reader.maxDoc(); i++) { - assertThat(result.get(i), equalTo(docs.contains(i))); - } - - // filter from mapper - result.clear(0, size); - assertThat(result.cardinality(), equalTo(0)); - result.or(strMapper.fieldDataTermsFilter(cTerms, parseContext) - .getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); - assertThat(result.cardinality(), equalTo(docs.size())); - for (int i = 0; i < reader.maxDoc(); i++) { - assertThat(result.get(i), equalTo(docs.contains(i))); - } - - result.clear(0, size); - assertThat(result.cardinality(), equalTo(0)); - - // filter on a numeric field using BytesRef terms - // should not match any docs - hFilter = FieldDataTermsFilter.newBytes(getFieldData(lngMapper), hTerms); - result.or(hFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); - assertThat(result.cardinality(), equalTo(0)); - - // filter on a numeric field using BytesRef terms - // should not match any docs - hFilter = FieldDataTermsFilter.newBytes(getFieldData(dblMapper), hTerms); - result.or(hFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); - assertThat(result.cardinality(), equalTo(0)); - } - - @Test - public void testLongs() throws Exception { - List docs = Arrays.asList(1, 5, 7); - - LongOpenHashSet hTerms = new LongOpenHashSet(); - List cTerms = new ArrayList<>(docs.size()); - for (int i = 0; i < docs.size(); i++) { - long term = docs.get(i).longValue(); - hTerms.add(term); - cTerms.add(term); - } - - FieldDataTermsFilter hFilter = FieldDataTermsFilter.newLongs(getFieldData(lngMapper), hTerms); - - int size = reader.maxDoc(); - FixedBitSet result = new FixedBitSet(size); - - result.clear(0, size); - assertThat(result.cardinality(), equalTo(0)); - result.or(hFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); - assertThat(result.cardinality(), equalTo(docs.size())); - for (int i = 0; i < reader.maxDoc(); i++) { - assertThat(result.get(i), equalTo(docs.contains(i))); - } - - // filter from mapper - result.clear(0, size); - assertThat(result.cardinality(), equalTo(0)); - result.or(lngMapper.fieldDataTermsFilter(cTerms, parseContext) - .getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); - assertThat(result.cardinality(), equalTo(docs.size())); - for (int i = 0; i < reader.maxDoc(); i++) { - assertThat(result.get(i), equalTo(docs.contains(i))); - } - - hFilter = FieldDataTermsFilter.newLongs(getFieldData(dblMapper), hTerms); - assertNull(hFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs())); - } - - @Test - public void testDoubles() throws Exception { - List docs = Arrays.asList(1, 5, 7); - - DoubleOpenHashSet hTerms = new DoubleOpenHashSet(); - List cTerms = new ArrayList<>(docs.size()); - for (int i = 0; i < docs.size(); i++) { - double term = Double.valueOf(docs.get(i)); - hTerms.add(term); - cTerms.add(term); - } - - FieldDataTermsFilter hFilter = FieldDataTermsFilter.newDoubles(getFieldData(dblMapper), hTerms); - - int size = reader.maxDoc(); - FixedBitSet result = new FixedBitSet(size); - - result.clear(0, size); - assertThat(result.cardinality(), equalTo(0)); - result.or(hFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); - assertThat(result.cardinality(), equalTo(docs.size())); - for (int i = 0; i < reader.maxDoc(); i++) { - assertThat(result.get(i), equalTo(docs.contains(i))); - } - - // filter from mapper - result.clear(0, size); - assertThat(result.cardinality(), equalTo(0)); - result.or(dblMapper.fieldDataTermsFilter(cTerms, parseContext) - .getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); - assertThat(result.cardinality(), equalTo(docs.size())); - for (int i = 0; i < reader.maxDoc(); i++) { - assertThat(result.get(i), equalTo(docs.contains(i))); - } - - hFilter = FieldDataTermsFilter.newDoubles(getFieldData(lngMapper), hTerms); - assertNull(hFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs())); - } - - @Test - public void testNoTerms() throws Exception { - FieldDataTermsFilter hFilterBytes = FieldDataTermsFilter.newBytes(getFieldData(strMapper), new ObjectOpenHashSet()); - FieldDataTermsFilter hFilterLongs = FieldDataTermsFilter.newLongs(getFieldData(lngMapper), new LongOpenHashSet()); - FieldDataTermsFilter hFilterDoubles = FieldDataTermsFilter.newDoubles(getFieldData(dblMapper), new DoubleOpenHashSet()); - assertNull(hFilterBytes.getDocIdSet(reader.getContext(), reader.getLiveDocs())); - assertNull(hFilterLongs.getDocIdSet(reader.getContext(), reader.getLiveDocs())); - assertNull(hFilterDoubles.getDocIdSet(reader.getContext(), reader.getLiveDocs())); - } -} diff --git a/src/test/java/org/elasticsearch/index/search/child/ChildrenConstantScoreQueryTests.java b/src/test/java/org/elasticsearch/index/search/child/ChildrenConstantScoreQueryTests.java index 6dff9747127..a8f319be0b5 100644 --- a/src/test/java/org/elasticsearch/index/search/child/ChildrenConstantScoreQueryTests.java +++ b/src/test/java/org/elasticsearch/index/search/child/ChildrenConstantScoreQueryTests.java @@ -65,12 +65,10 @@ import java.util.NavigableSet; import java.util.Random; import java.util.TreeSet; -import static org.elasticsearch.index.query.FilterBuilders.hasChildFilter; -import static org.elasticsearch.index.query.FilterBuilders.notFilter; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; import static org.elasticsearch.index.query.QueryBuilders.hasChildQuery; +import static org.elasticsearch.index.query.QueryBuilders.notQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.hamcrest.Matchers.equalTo; @@ -256,12 +254,12 @@ public class ChildrenConstantScoreQueryTests extends AbstractChildTests { .setShortCircuitCutoff(shortCircuitParentDocSet); } else { queryBuilder = constantScoreQuery( - hasChildFilter("child", termQuery("field1", childValue)) + hasChildQuery("child", termQuery("field1", childValue)) .setShortCircuitCutoff(shortCircuitParentDocSet) ); } // Using a FQ, will invoke / test the Scorer#advance(..) and also let the Weight#scorer not get live docs as acceptedDocs - queryBuilder = filteredQuery(queryBuilder, notFilter(termFilter("filter", "me"))); + queryBuilder = filteredQuery(queryBuilder, notQuery(termQuery("filter", "me"))); Query query = parseQuery(queryBuilder); BitSetCollector collector = new BitSetCollector(indexReader.maxDoc()); diff --git a/src/test/java/org/elasticsearch/index/search/child/ChildrenQueryTests.java b/src/test/java/org/elasticsearch/index/search/child/ChildrenQueryTests.java index 52ffbf022ea..ed235a07e6f 100644 --- a/src/test/java/org/elasticsearch/index/search/child/ChildrenQueryTests.java +++ b/src/test/java/org/elasticsearch/index/search/child/ChildrenQueryTests.java @@ -79,14 +79,13 @@ import java.util.NavigableMap; import java.util.Random; import java.util.TreeMap; -import static org.elasticsearch.index.query.FilterBuilders.notFilter; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; -import static org.elasticsearch.index.query.FilterBuilders.typeFilter; import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.hasChildQuery; +import static org.elasticsearch.index.query.QueryBuilders.notQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; +import static org.elasticsearch.index.query.QueryBuilders.typeQuery; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; @@ -241,7 +240,7 @@ public class ChildrenQueryTests extends AbstractChildTests { .maxChildren(maxChildren) .setShortCircuitCutoff(shortCircuitParentDocSet); // Using a FQ, will invoke / test the Scorer#advance(..) and also let the Weight#scorer not get live docs as acceptedDocs - queryBuilder = filteredQuery(queryBuilder, notFilter(termFilter("filter", "me"))); + queryBuilder = filteredQuery(queryBuilder, notQuery(termQuery("filter", "me"))); Query query = parseQuery(queryBuilder); BitSetCollector collector = new BitSetCollector(indexReader.maxDoc()); int numHits = 1 + random().nextInt(25); @@ -389,13 +388,14 @@ public class ChildrenQueryTests extends AbstractChildTests { ((TestSearchContext)context).setSearcher(new ContextIndexSearcher(context, engineSearcher)); // child query that returns the score as the value of "childScore" for each child document, with the parent's score determined by the score type - QueryBuilder childQueryBuilder = functionScoreQuery(typeFilter("child")).add(new FieldValueFactorFunctionBuilder(CHILD_SCORE_NAME)); + QueryBuilder childQueryBuilder = functionScoreQuery(typeQuery("child")).add(new FieldValueFactorFunctionBuilder(CHILD_SCORE_NAME)); QueryBuilder queryBuilder = hasChildQuery("child", childQueryBuilder) .scoreType(scoreType.name().toLowerCase(Locale.ENGLISH)) .setShortCircuitCutoff(parentDocs); // Perform the search for the documents using the selected score type - TopDocs docs = searcher.search(parseQuery(queryBuilder), parentDocs); + Query query = parseQuery(queryBuilder); + TopDocs docs = searcher.search(query, parentDocs); assertThat("Expected all parents", docs.totalHits, is(parentDocs)); // score should be descending (just a sanity check) diff --git a/src/test/java/org/elasticsearch/index/search/child/ParentConstantScoreQueryTests.java b/src/test/java/org/elasticsearch/index/search/child/ParentConstantScoreQueryTests.java index feb320942b0..7f1e83771a4 100644 --- a/src/test/java/org/elasticsearch/index/search/child/ParentConstantScoreQueryTests.java +++ b/src/test/java/org/elasticsearch/index/search/child/ParentConstantScoreQueryTests.java @@ -64,12 +64,10 @@ import java.util.NavigableSet; import java.util.Random; import java.util.TreeSet; -import static org.elasticsearch.index.query.FilterBuilders.hasParentFilter; -import static org.elasticsearch.index.query.FilterBuilders.notFilter; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; import static org.elasticsearch.index.query.QueryBuilders.hasParentQuery; +import static org.elasticsearch.index.query.QueryBuilders.notQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; /** @@ -210,10 +208,10 @@ public class ParentConstantScoreQueryTests extends AbstractChildTests { if (random().nextBoolean()) { queryBuilder = hasParentQuery("parent", termQuery("field1", parentValue)); } else { - queryBuilder = constantScoreQuery(hasParentFilter("parent", termFilter("field1", parentValue))); + queryBuilder = constantScoreQuery(hasParentQuery("parent", termQuery("field1", parentValue))); } // Using a FQ, will invoke / test the Scorer#advance(..) and also let the Weight#scorer not get live docs as acceptedDocs - queryBuilder = filteredQuery(queryBuilder, notFilter(termFilter("filter", "me"))); + queryBuilder = filteredQuery(queryBuilder, notQuery(termQuery("filter", "me"))); Query query = parseQuery(queryBuilder); BitSetCollector collector = new BitSetCollector(indexReader.maxDoc()); searcher.search(query, collector); diff --git a/src/test/java/org/elasticsearch/index/search/child/ParentQueryTests.java b/src/test/java/org/elasticsearch/index/search/child/ParentQueryTests.java index 0614a6c2439..6b6a260ee64 100644 --- a/src/test/java/org/elasticsearch/index/search/child/ParentQueryTests.java +++ b/src/test/java/org/elasticsearch/index/search/child/ParentQueryTests.java @@ -70,11 +70,10 @@ import java.util.NavigableMap; import java.util.Random; import java.util.TreeMap; -import static org.elasticsearch.index.query.FilterBuilders.notFilter; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; import static org.elasticsearch.index.query.QueryBuilders.hasParentQuery; +import static org.elasticsearch.index.query.QueryBuilders.notQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; public class ParentQueryTests extends AbstractChildTests { @@ -211,7 +210,7 @@ public class ParentQueryTests extends AbstractChildTests { String parentValue = parentValues[random().nextInt(numUniqueParentValues)]; QueryBuilder queryBuilder = hasParentQuery("parent", constantScoreQuery(termQuery("field1", parentValue))); // Using a FQ, will invoke / test the Scorer#advance(..) and also let the Weight#scorer not get live docs as acceptedDocs - queryBuilder = filteredQuery(queryBuilder, notFilter(termFilter("filter", "me"))); + queryBuilder = filteredQuery(queryBuilder, notQuery(termQuery("filter", "me"))); Query query = parseQuery(queryBuilder); BitSetCollector collector = new BitSetCollector(indexReader.maxDoc()); diff --git a/src/test/java/org/elasticsearch/indices/stats/IndexStatsTests.java b/src/test/java/org/elasticsearch/indices/stats/IndexStatsTests.java index d992991fa18..96d875b2e18 100644 --- a/src/test/java/org/elasticsearch/indices/stats/IndexStatsTests.java +++ b/src/test/java/org/elasticsearch/indices/stats/IndexStatsTests.java @@ -40,12 +40,11 @@ import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.cache.filter.FilterCacheModule; -import org.elasticsearch.index.cache.filter.FilterCacheStats; import org.elasticsearch.index.cache.filter.FilterCacheModule.FilterCacheSettings; +import org.elasticsearch.index.cache.filter.FilterCacheStats; import org.elasticsearch.index.cache.filter.index.IndexFilterCache; import org.elasticsearch.index.merge.policy.TieredMergePolicyProvider; import org.elasticsearch.index.merge.scheduler.ConcurrentMergeSchedulerProvider; -import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.store.IndexStore; import org.elasticsearch.indices.cache.query.IndicesQueryCache; @@ -62,7 +61,9 @@ import java.util.Random; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAllSuccessful; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; @@ -153,11 +154,11 @@ public class IndexStatsTests extends ElasticsearchIntegrationTest { // sort to load it to field data and filter to load filter cache client().prepareSearch() - .setPostFilter(FilterBuilders.termFilter("field", "value1")) + .setPostFilter(QueryBuilders.termQuery("field", "value1")) .addSort("field", SortOrder.ASC) .execute().actionGet(); client().prepareSearch() - .setPostFilter(FilterBuilders.termFilter("field", "value2")) + .setPostFilter(QueryBuilders.termQuery("field", "value2")) .addSort("field", SortOrder.ASC) .execute().actionGet(); diff --git a/src/test/java/org/elasticsearch/indices/template/SimpleIndexTemplateTests.java b/src/test/java/org/elasticsearch/indices/template/SimpleIndexTemplateTests.java index f2487ec9e4f..2901db9a5f3 100644 --- a/src/test/java/org/elasticsearch/indices/template/SimpleIndexTemplateTests.java +++ b/src/test/java/org/elasticsearch/indices/template/SimpleIndexTemplateTests.java @@ -34,7 +34,7 @@ import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.cluster.metadata.AliasMetaData; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.indices.IndexTemplateAlreadyExistsException; import org.elasticsearch.indices.InvalidAliasNameException; @@ -46,7 +46,7 @@ import java.util.Arrays; import java.util.List; import java.util.Set; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; import static org.hamcrest.Matchers.*; @@ -346,7 +346,7 @@ public class SimpleIndexTemplateTests extends ElasticsearchIntegrationTest { .addAlias(new Alias("templated_alias-{index}")) .addAlias(new Alias("filtered_alias").filter("{\"type\":{\"value\":\"type2\"}}")) .addAlias(new Alias("complex_filtered_alias") - .filter(FilterBuilders.termsFilter("_type", "typeX", "typeY", "typeZ").execution("bool"))) + .filter(QueryBuilders.termsQuery("_type", "typeX", "typeY", "typeZ").execution("bool"))) .get(); assertAcked(prepareCreate("test_index").addMapping("type1").addMapping("type2").addMapping("typeX").addMapping("typeY").addMapping("typeZ")); @@ -468,8 +468,8 @@ public class SimpleIndexTemplateTests extends ElasticsearchIntegrationTest { public void testDuplicateAlias() throws Exception { client().admin().indices().preparePutTemplate("template_1") .setTemplate("te*") - .addAlias(new Alias("my_alias").filter(termFilter("field", "value1"))) - .addAlias(new Alias("my_alias").filter(termFilter("field", "value2"))) + .addAlias(new Alias("my_alias").filter(termQuery("field", "value1"))) + .addAlias(new Alias("my_alias").filter(termQuery("field", "value2"))) .get(); GetIndexTemplatesResponse response = client().admin().indices().prepareGetTemplates("template_1").get(); @@ -497,7 +497,7 @@ public class SimpleIndexTemplateTests extends ElasticsearchIntegrationTest { } catch(IllegalArgumentException e) { assertThat(e.getMessage(), equalTo("failed to parse filter for alias [invalid_alias]")); assertThat(e.getCause(), instanceOf(QueryParsingException.class)); - assertThat(e.getCause().getMessage(), equalTo("No filter registered for [invalid]")); + assertThat(e.getCause().getMessage(), equalTo("No query registered for [invalid]")); } } @@ -571,7 +571,7 @@ public class SimpleIndexTemplateTests extends ElasticsearchIntegrationTest { .setOrder(0) .addAlias(new Alias("alias1")) .addAlias(new Alias("{index}-alias")) - .addAlias(new Alias("alias3").filter(FilterBuilders.missingFilter("test"))) + .addAlias(new Alias("alias3").filter(QueryBuilders.missingQuery("test"))) .addAlias(new Alias("alias4")).get(); client().admin().indices().preparePutTemplate("template2") @@ -609,25 +609,25 @@ public class SimpleIndexTemplateTests extends ElasticsearchIntegrationTest { .setTemplate("a*") .setOrder(0) .addMapping("test", "field", "type=string") - .addAlias(new Alias("alias1").filter(termFilter("field", "value"))).get(); + .addAlias(new Alias("alias1").filter(termQuery("field", "value"))).get(); // Indexing into b should succeed, because the field mapping for field 'field' is defined in the _default_ mapping and the test type exists. client().admin().indices().preparePutTemplate("template2") .setTemplate("b*") .setOrder(0) .addMapping("_default_", "field", "type=string") .addMapping("test") - .addAlias(new Alias("alias2").filter(termFilter("field", "value"))).get(); + .addAlias(new Alias("alias2").filter(termQuery("field", "value"))).get(); // Indexing into c should succeed, because the field mapping for field 'field' is defined in the _default_ mapping. client().admin().indices().preparePutTemplate("template3") .setTemplate("c*") .setOrder(0) .addMapping("_default_", "field", "type=string") - .addAlias(new Alias("alias3").filter(termFilter("field", "value"))).get(); + .addAlias(new Alias("alias3").filter(termQuery("field", "value"))).get(); // Indexing into d index should fail, since there is field with name 'field' in the mapping client().admin().indices().preparePutTemplate("template4") .setTemplate("d*") .setOrder(0) - .addAlias(new Alias("alias4").filter(termFilter("field", "value"))).get(); + .addAlias(new Alias("alias4").filter(termQuery("field", "value"))).get(); client().prepareIndex("a1", "test", "test").setSource("{}").get(); BulkResponse response = client().prepareBulk().add(new IndexRequest("a2", "test", "test").source("{}")).get(); diff --git a/src/test/java/org/elasticsearch/nested/SimpleNestedTests.java b/src/test/java/org/elasticsearch/nested/SimpleNestedTests.java index a788964bbfb..0f5a03180b2 100644 --- a/src/test/java/org/elasticsearch/nested/SimpleNestedTests.java +++ b/src/test/java/org/elasticsearch/nested/SimpleNestedTests.java @@ -19,7 +19,6 @@ package org.elasticsearch.nested; -import com.carrotsearch.randomizedtesting.annotations.Seed; import org.apache.lucene.search.Explanation; import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus; import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse; @@ -34,7 +33,6 @@ import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.search.sort.SortOrder; @@ -47,10 +45,25 @@ import java.util.List; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.*; -import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; -import static org.hamcrest.Matchers.*; +import static org.elasticsearch.index.query.QueryBuilders.boolQuery; +import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; +import static org.elasticsearch.index.query.QueryBuilders.nestedQuery; +import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAllSuccessful; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.arrayContainingInAnyOrder; +import static org.hamcrest.Matchers.arrayWithSize; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; public class SimpleNestedTests extends ElasticsearchIntegrationTest { @@ -136,7 +149,7 @@ public class SimpleNestedTests extends ElasticsearchIntegrationTest { assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); // filter - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), nestedFilter("nested1", + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), nestedQuery("nested1", boolQuery().must(termQuery("nested1.n_field1", "n_value1_1")).must(termQuery("nested1.n_field2", "n_value2_1"))))).execute().actionGet(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); @@ -343,7 +356,7 @@ public class SimpleNestedTests extends ElasticsearchIntegrationTest { .endObject().endObject().endObject())); client().admin().indices().prepareAliases() - .addAlias("test", "alias1", FilterBuilders.termFilter("field1", "value1")).execute().actionGet(); + .addAlias("test", "alias1", QueryBuilders.termQuery("field1", "value1")).execute().actionGet(); ensureGreen(); @@ -540,7 +553,7 @@ public class SimpleNestedTests extends ElasticsearchIntegrationTest { .setTypes("type1") .setQuery(QueryBuilders.matchAllQuery()) .addSort(SortBuilders.scriptSort("_fields['nested1.field1'].value", "number") - .setNestedFilter(rangeFilter("nested1.field1").from(1).to(3)) + .setNestedFilter(rangeQuery("nested1.field1").from(1).to(3)) .setNestedPath("nested1").sortMode("avg").order(SortOrder.DESC)) .execute().actionGet(); @@ -661,7 +674,7 @@ public class SimpleNestedTests extends ElasticsearchIntegrationTest { SearchRequestBuilder searchRequestBuilder = client().prepareSearch("test").setTypes("type1") .setQuery(QueryBuilders.matchAllQuery()) - .addSort(SortBuilders.fieldSort("nested1.field1").setNestedFilter(termFilter("nested1.field2", true)).missing(10).order(SortOrder.ASC)); + .addSort(SortBuilders.fieldSort("nested1.field1").setNestedFilter(termQuery("nested1.field2", true)).missing(10).order(SortOrder.ASC)); if (randomBoolean()) { searchRequestBuilder.setScroll("10m"); @@ -678,7 +691,7 @@ public class SimpleNestedTests extends ElasticsearchIntegrationTest { assertThat(searchResponse.getHits().hits()[2].sortValues()[0].toString(), equalTo("10")); searchRequestBuilder = client().prepareSearch("test").setTypes("type1").setQuery(QueryBuilders.matchAllQuery()) - .addSort(SortBuilders.fieldSort("nested1.field1").setNestedFilter(termFilter("nested1.field2", true)).missing(10).order(SortOrder.DESC)); + .addSort(SortBuilders.fieldSort("nested1.field1").setNestedFilter(termQuery("nested1.field2", true)).missing(10).order(SortOrder.DESC)); if (randomBoolean()) { searchRequestBuilder.setScroll("10m"); @@ -839,7 +852,7 @@ public class SimpleNestedTests extends ElasticsearchIntegrationTest { .addSort( SortBuilders.fieldSort("parent.child.child_values") .setNestedPath("parent.child") - .setNestedFilter(FilterBuilders.termFilter("parent.child.filter", true)) + .setNestedFilter(QueryBuilders.termQuery("parent.child.filter", true)) .order(SortOrder.ASC) ) .execute().actionGet(); @@ -857,7 +870,7 @@ public class SimpleNestedTests extends ElasticsearchIntegrationTest { .setQuery(matchAllQuery()) .addSort( SortBuilders.fieldSort("parent.child.child_values") - .setNestedFilter(FilterBuilders.termFilter("parent.child.filter", true)) + .setNestedFilter(QueryBuilders.termQuery("parent.child.filter", true)) .order(SortOrder.ASC) ) .execute().actionGet(); @@ -876,7 +889,7 @@ public class SimpleNestedTests extends ElasticsearchIntegrationTest { .addSort( SortBuilders.fieldSort("parent.parent_values") .setNestedPath("parent.child") - .setNestedFilter(FilterBuilders.termFilter("parent.filter", false)) + .setNestedFilter(QueryBuilders.termQuery("parent.filter", false)) .order(SortOrder.ASC) ) .execute().actionGet(); @@ -895,7 +908,7 @@ public class SimpleNestedTests extends ElasticsearchIntegrationTest { .addSort( SortBuilders.fieldSort("parent.child.child_values") .setNestedPath("parent.child") - .setNestedFilter(FilterBuilders.termFilter("parent.filter", false)) + .setNestedFilter(QueryBuilders.termQuery("parent.filter", false)) .order(SortOrder.ASC) ) .execute().actionGet(); @@ -915,7 +928,7 @@ public class SimpleNestedTests extends ElasticsearchIntegrationTest { .setQuery(matchAllQuery()) .addSort( SortBuilders.fieldSort("parent.child.child_obj.value") - .setNestedFilter(FilterBuilders.termFilter("parent.child.filter", true)) + .setNestedFilter(QueryBuilders.termQuery("parent.child.filter", true)) .order(SortOrder.ASC) ) .execute().actionGet(); @@ -975,7 +988,7 @@ public class SimpleNestedTests extends ElasticsearchIntegrationTest { .addSort( SortBuilders.fieldSort("parent.child.child_values") .setNestedPath("parent.child") - .setNestedFilter(FilterBuilders.termFilter("parent.child.filter", true)) + .setNestedFilter(QueryBuilders.termQuery("parent.child.filter", true)) .sortMode("sum") .order(SortOrder.ASC) ) @@ -1035,7 +1048,7 @@ public class SimpleNestedTests extends ElasticsearchIntegrationTest { .addSort( SortBuilders.fieldSort("parent.child.child_values") .setNestedPath("parent.child") - .setNestedFilter(FilterBuilders.termFilter("parent.child.filter", true)) + .setNestedFilter(QueryBuilders.termQuery("parent.child.filter", true)) .sortMode("avg") .order(SortOrder.ASC) ) @@ -1175,7 +1188,7 @@ public class SimpleNestedTests extends ElasticsearchIntegrationTest { .addSort(SortBuilders.fieldSort("users.first") .order(SortOrder.ASC) .setNestedPath("users") - .setNestedFilter(nestedFilter("users.workstations", termFilter("users.workstations.stationid", "s5")))) + .setNestedFilter(nestedQuery("users.workstations", termQuery("users.workstations.stationid", "s5")))) .get(); assertNoFailures(searchResponse); assertHitCount(searchResponse, 2); diff --git a/src/test/java/org/elasticsearch/percolator/PercolatorTests.java b/src/test/java/org/elasticsearch/percolator/PercolatorTests.java index 91f5afa7b0b..170a54240e0 100644 --- a/src/test/java/org/elasticsearch/percolator/PercolatorTests.java +++ b/src/test/java/org/elasticsearch/percolator/PercolatorTests.java @@ -41,7 +41,6 @@ import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.engine.DocumentMissingException; import org.elasticsearch.index.engine.VersionConflictEngineException; import org.elasticsearch.index.percolator.PercolatorException; -import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryParsingException; @@ -50,7 +49,6 @@ import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.highlight.HighlightBuilder; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.test.ElasticsearchIntegrationTest; -import org.elasticsearch.test.hamcrest.ElasticsearchAssertions; import org.junit.Test; import java.io.IOException; @@ -72,8 +70,6 @@ import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilde import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.smileBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.yamlBuilder; -import static org.elasticsearch.index.query.FilterBuilders.rangeFilter; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; @@ -236,49 +232,6 @@ public class PercolatorTests extends ElasticsearchIntegrationTest { assertMatchCount(response, 1l); assertThat(response.getMatches(), arrayWithSize(1)); assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContaining("test1")); - - // add a range query (cached) - // add a query - client().prepareIndex("test", PercolatorService.TYPE_NAME, "test3") - .setSource( - XContentFactory.jsonBuilder().startObject().field("query", - constantScoreQuery(rangeFilter("field1").from(1).to(5).includeLower(true).setExecution("fielddata")) - ).endObject() - ) - .execute().actionGet(); - - response = client().preparePercolate() - .setIndices("test").setDocumentType("type1") - .setSource(doc).execute().actionGet(); - ElasticsearchAssertions.assertFailures(response); - // TODO: with doc values by default, fielddata execution mode causes a doc values - // lookup, but memory index doesn't have doc values. we should consider just removing - // execution mode. - //assertMatchCount(response, 2l); - //assertThat(response.getMatches(), arrayWithSize(2)); - //assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("test1", "test3")); - } - - @Test - public void testRangeFilterThatUsesFD() throws Exception { - client().admin().indices().prepareCreate("test") - .addMapping("type1", "field1", "type=long,doc_values=false") - .get(); - - - client().prepareIndex("test", PercolatorService.TYPE_NAME, "1") - .setSource( - XContentFactory.jsonBuilder().startObject().field("query", - constantScoreQuery(rangeFilter("field1").from(1).to(5).setExecution("fielddata")) - ).endObject() - ).get(); - - PercolateResponse response = client().preparePercolate() - .setIndices("test").setDocumentType("type1") - .setPercolateDoc(PercolateSourceBuilder.docBuilder().setDoc("field1", 3)).get(); - assertMatchCount(response, 1l); - assertThat(response.getMatches(), arrayWithSize(1)); - assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContaining("1")); } @Test @@ -960,9 +913,9 @@ public class PercolatorTests extends ElasticsearchIntegrationTest { public void testPercolateWithAliasFilter() throws Exception { assertAcked(prepareCreate("my-index") .addMapping(PercolatorService.TYPE_NAME, "a", "type=string,index=not_analyzed") - .addAlias(new Alias("a").filter(FilterBuilders.termFilter("a", "a"))) - .addAlias(new Alias("b").filter(FilterBuilders.termFilter("a", "b"))) - .addAlias(new Alias("c").filter(FilterBuilders.termFilter("a", "c"))) + .addAlias(new Alias("a").filter(QueryBuilders.termQuery("a", "a"))) + .addAlias(new Alias("b").filter(QueryBuilders.termQuery("a", "b"))) + .addAlias(new Alias("c").filter(QueryBuilders.termQuery("a", "c"))) ); client().prepareIndex("my-index", PercolatorService.TYPE_NAME, "1") .setSource(jsonBuilder().startObject().field("query", matchAllQuery()).field("a", "a").endObject()) @@ -1007,7 +960,7 @@ public class PercolatorTests extends ElasticsearchIntegrationTest { .setIndices("a") .setDocumentType("my-type") .setPercolateDoc(new PercolateSourceBuilder.DocBuilder().setDoc("{}")) - .setPercolateFilter(FilterBuilders.matchAllFilter()) + .setPercolateQuery(QueryBuilders.matchAllQuery()) .get(); assertNoFailures(response); assertThat(response.getCount(), equalTo(1l)); @@ -1017,7 +970,7 @@ public class PercolatorTests extends ElasticsearchIntegrationTest { .setIndices("b") .setDocumentType("my-type") .setPercolateDoc(new PercolateSourceBuilder.DocBuilder().setDoc("{}")) - .setPercolateFilter(FilterBuilders.matchAllFilter()) + .setPercolateQuery(QueryBuilders.matchAllQuery()) .get(); assertNoFailures(response); assertThat(response.getCount(), equalTo(1l)); @@ -1028,7 +981,7 @@ public class PercolatorTests extends ElasticsearchIntegrationTest { .setIndices("c") .setDocumentType("my-type") .setPercolateDoc(new PercolateSourceBuilder.DocBuilder().setDoc("{}")) - .setPercolateFilter(FilterBuilders.matchAllFilter()) + .setPercolateQuery(QueryBuilders.matchAllQuery()) .get(); assertNoFailures(response); assertThat(response.getCount(), equalTo(0l)); @@ -1230,7 +1183,7 @@ public class PercolatorTests extends ElasticsearchIntegrationTest { .setIndices("my-index").setDocumentType("my-type") .setOnlyCount(onlyCount) .setPercolateDoc(docBuilder().setDoc("field", "value")) - .setPercolateFilter(termFilter("level", 1 + randomInt(numLevels - 1))) + .setPercolateQuery(termQuery("level", 1 + randomInt(numLevels - 1))) .execute().actionGet(); assertMatchCount(response, numQueriesPerLevel); if (!onlyCount) { @@ -1246,7 +1199,7 @@ public class PercolatorTests extends ElasticsearchIntegrationTest { .setOnlyCount(onlyCount) .setSize(size) .setPercolateDoc(docBuilder().setDoc("field", "value")) - .setPercolateFilter(termFilter("level", 1 + randomInt(numLevels - 1))) + .setPercolateQuery(termQuery("level", 1 + randomInt(numLevels - 1))) .execute().actionGet(); assertMatchCount(response, numQueriesPerLevel); if (!onlyCount) { @@ -1680,9 +1633,9 @@ public class PercolatorTests extends ElasticsearchIntegrationTest { logger.info("--> register a query"); client().prepareIndex("test", PercolatorService.TYPE_NAME, "1") .setSource(jsonBuilder().startObject() - .field("query", QueryBuilders.constantScoreQuery(FilterBuilders.andFilter( - FilterBuilders.queryFilter(QueryBuilders.queryStringQuery("root")), - FilterBuilders.termFilter("message", "tree")))) + .field("query", QueryBuilders.constantScoreQuery(QueryBuilders.andQuery( + QueryBuilders.queryStringQuery("root"), + QueryBuilders.termQuery("message", "tree")))) .endObject()) .setRefresh(true) .execute().actionGet(); @@ -1834,7 +1787,7 @@ public class PercolatorTests extends ElasticsearchIntegrationTest { PercolateResponse response = client().preparePercolate() .setIndices("test").setDocumentType("type") .setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field", "value").endObject())) - .setPercolateFilter(FilterBuilders.matchAllFilter()) + .setPercolateQuery(QueryBuilders.matchAllQuery()) .get(); assertMatchCount(response, 1l); assertThat(response.getMatches(), arrayWithSize(1)); @@ -1876,7 +1829,7 @@ public class PercolatorTests extends ElasticsearchIntegrationTest { .setSource(jsonBuilder().startObject().field("query", rangeQuery("timestamp").from("now-1d").to("now")).endObject()) .get(); client().prepareIndex("test", PercolatorService.TYPE_NAME, "2") - .setSource(jsonBuilder().startObject().field("query", constantScoreQuery(rangeFilter("timestamp").from("now-1d").to("now"))).endObject()) + .setSource(jsonBuilder().startObject().field("query", constantScoreQuery(rangeQuery("timestamp").from("now-1d").to("now"))).endObject()) .get(); logger.info("--> Percolate doc with field1=b"); diff --git a/src/test/java/org/elasticsearch/script/GroovyScriptTests.java b/src/test/java/org/elasticsearch/script/GroovyScriptTests.java index 657d2bc361e..9e7776e0dcc 100644 --- a/src/test/java/org/elasticsearch/script/GroovyScriptTests.java +++ b/src/test/java/org/elasticsearch/script/GroovyScriptTests.java @@ -31,7 +31,7 @@ import org.junit.Test; import java.util.List; import static com.google.common.collect.Lists.newArrayList; -import static org.elasticsearch.index.query.FilterBuilders.scriptFilter; +import static org.elasticsearch.index.query.QueryBuilders.scriptQuery; import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; @@ -73,7 +73,7 @@ public class GroovyScriptTests extends ElasticsearchIntegrationTest { } indexRandom(true, false, reqs); try { - client().prepareSearch("test").setQuery(constantScoreQuery(scriptFilter("1 == not_found").lang(GroovyScriptEngineService.NAME))).get(); + client().prepareSearch("test").setQuery(constantScoreQuery(scriptQuery("1 == not_found").lang(GroovyScriptEngineService.NAME))).get(); fail("should have thrown an exception"); } catch (SearchPhaseExecutionException e) { assertThat(e.toString()+ "should not contained NotSerializableTransportException", @@ -86,7 +86,7 @@ public class GroovyScriptTests extends ElasticsearchIntegrationTest { try { client().prepareSearch("test").setQuery(constantScoreQuery( - scriptFilter("assert false").lang("groovy"))).get(); + scriptQuery("assert false").lang("groovy"))).get(); fail("should have thrown an exception"); } catch (SearchPhaseExecutionException e) { assertThat(e.toString()+ "should not contained NotSerializableTransportException", diff --git a/src/test/java/org/elasticsearch/search/aggregations/EquivalenceTests.java b/src/test/java/org/elasticsearch/search/aggregations/EquivalenceTests.java index d318ed5ca7b..948fcc9aeea 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/EquivalenceTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/EquivalenceTests.java @@ -29,8 +29,8 @@ import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.FilterBuilders; -import org.elasticsearch.index.query.RangeFilterBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.index.query.RangeQueryBuilder; import org.elasticsearch.search.aggregations.Aggregator.SubAggCollectionMode; import org.elasticsearch.search.aggregations.bucket.filter.Filter; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; @@ -129,7 +129,7 @@ public class EquivalenceTests extends ElasticsearchIntegrationTest { SearchRequestBuilder reqBuilder = client().prepareSearch("idx").addAggregation(query); for (int i = 0; i < ranges.length; ++i) { - RangeFilterBuilder filter = FilterBuilders.rangeFilter("values"); + RangeQueryBuilder filter = QueryBuilders.rangeQuery("values"); if (ranges[i][0] != Double.NEGATIVE_INFINITY) { filter = filter.from(ranges[i][0]); } @@ -343,7 +343,7 @@ public class EquivalenceTests extends ElasticsearchIntegrationTest { indexRandom(true, client().prepareIndex("idx", "type").setSource("f", value)); ensureYellow("idx"); // only one document let's make sure all shards have an active primary SearchResponse response = client().prepareSearch("idx") - .addAggregation(filter("filter").filter(FilterBuilders.matchAllFilter()) + .addAggregation(filter("filter").filter(QueryBuilders.matchAllQuery()) .subAggregation(range("range") .field("f") .addUnboundedTo(6) diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/DoubleTermsTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/DoubleTermsTests.java index 3c632b299b0..29f596c03e1 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/DoubleTermsTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/DoubleTermsTests.java @@ -21,7 +21,7 @@ package org.elasticsearch.search.aggregations.bucket; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; import org.elasticsearch.search.aggregations.Aggregator.SubAggCollectionMode; import org.elasticsearch.search.aggregations.bucket.filter.Filter; @@ -896,7 +896,7 @@ public class DoubleTermsTests extends AbstractTermsTests { .field("num_tag") .collectMode(randomFrom(SubAggCollectionMode.values())) .order(Terms.Order.aggregation("filter", asc)) - .subAggregation(filter("filter").filter(FilterBuilders.matchAllFilter())) + .subAggregation(filter("filter").filter(QueryBuilders.matchAllQuery())) ).execute().actionGet(); @@ -934,8 +934,8 @@ public class DoubleTermsTests extends AbstractTermsTests { .field("num_tag") .collectMode(randomFrom(SubAggCollectionMode.values())) .order(Terms.Order.aggregation("filter1>filter2>max", asc)) - .subAggregation(filter("filter1").filter(FilterBuilders.matchAllFilter()) - .subAggregation(filter("filter2").filter(FilterBuilders.matchAllFilter()) + .subAggregation(filter("filter1").filter(QueryBuilders.matchAllQuery()) + .subAggregation(filter("filter2").filter(QueryBuilders.matchAllQuery()) .subAggregation(max("max").field(SINGLE_VALUED_FIELD_NAME)))) ).execute().actionGet(); diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/FilterTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/FilterTests.java index d35b9f654c2..032504b1a0a 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/FilterTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/FilterTests.java @@ -22,8 +22,8 @@ import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.AndFilterBuilder; -import org.elasticsearch.index.query.FilterBuilder; +import org.elasticsearch.index.query.AndQueryBuilder; +import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.aggregations.bucket.filter.Filter; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.metrics.avg.Avg; @@ -35,9 +35,8 @@ import java.util.ArrayList; import java.util.List; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.matchAllFilter; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.aggregations.AggregationBuilders.avg; import static org.elasticsearch.search.aggregations.AggregationBuilders.filter; import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram; @@ -95,7 +94,7 @@ public class FilterTests extends ElasticsearchIntegrationTest { @Test public void simple() throws Exception { SearchResponse response = client().prepareSearch("idx") - .addAggregation(filter("tag1").filter(termFilter("tag", "tag1"))) + .addAggregation(filter("tag1").filter(termQuery("tag", "tag1"))) .execute().actionGet(); assertSearchResponse(response); @@ -111,7 +110,7 @@ public class FilterTests extends ElasticsearchIntegrationTest { // https://github.com/elasticsearch/elasticsearch/issues/8438 @Test public void emptyFilterDeclarations() throws Exception { - FilterBuilder emptyFilter = new AndFilterBuilder(); + QueryBuilder emptyFilter = new AndQueryBuilder(); SearchResponse response = client().prepareSearch("idx").addAggregation(filter("tag1").filter(emptyFilter)).execute().actionGet(); assertSearchResponse(response); @@ -125,7 +124,7 @@ public class FilterTests extends ElasticsearchIntegrationTest { public void withSubAggregation() throws Exception { SearchResponse response = client().prepareSearch("idx") .addAggregation(filter("tag1") - .filter(termFilter("tag", "tag1")) + .filter(termQuery("tag", "tag1")) .subAggregation(avg("avg_value").field("value"))) .execute().actionGet(); @@ -156,7 +155,7 @@ public class FilterTests extends ElasticsearchIntegrationTest { try { client().prepareSearch("idx") .addAggregation(filter("tag1") - .filter(termFilter("tag", "tag1")) + .filter(termQuery("tag", "tag1")) .subAggregation(avg("avg_value"))) .execute().actionGet(); @@ -172,7 +171,7 @@ public class FilterTests extends ElasticsearchIntegrationTest { SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx") .setQuery(matchAllQuery()) .addAggregation(histogram("histo").field("value").interval(1l).minDocCount(0) - .subAggregation(filter("filter").filter(matchAllFilter()))) + .subAggregation(filter("filter").filter(matchAllQuery()))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(2l)); diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/FiltersTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/FiltersTests.java index eeb59a2c3fa..4aaa9f2b352 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/FiltersTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/FiltersTests.java @@ -23,8 +23,8 @@ import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.AndFilterBuilder; -import org.elasticsearch.index.query.FilterBuilder; +import org.elasticsearch.index.query.AndQueryBuilder; +import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.aggregations.bucket.filters.Filters; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.metrics.avg.Avg; @@ -38,8 +38,8 @@ import java.util.Iterator; import java.util.List; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.matchAllFilter; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; +import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.search.aggregations.AggregationBuilders.avg; import static org.elasticsearch.search.aggregations.AggregationBuilders.filters; @@ -105,8 +105,8 @@ public class FiltersTests extends ElasticsearchIntegrationTest { SearchResponse response = client().prepareSearch("idx") .addAggregation( filters("tags") - .filter("tag1", termFilter("tag", "tag1")) - .filter("tag2", termFilter("tag", "tag2"))) + .filter("tag1", termQuery("tag", "tag1")) + .filter("tag2", termQuery("tag", "tag2"))) .execute().actionGet(); assertSearchResponse(response); @@ -130,9 +130,9 @@ public class FiltersTests extends ElasticsearchIntegrationTest { // https://github.com/elasticsearch/elasticsearch/issues/8438 @Test public void emptyFilterDeclarations() throws Exception { - FilterBuilder emptyFilter = new AndFilterBuilder(); + QueryBuilder emptyFilter = new AndQueryBuilder(); SearchResponse response = client().prepareSearch("idx") - .addAggregation(filters("tags").filter("all", emptyFilter).filter("tag1", termFilter("tag", "tag1"))).execute() + .addAggregation(filters("tags").filter("all", emptyFilter).filter("tag1", termQuery("tag", "tag1"))).execute() .actionGet(); assertSearchResponse(response); @@ -152,8 +152,8 @@ public class FiltersTests extends ElasticsearchIntegrationTest { SearchResponse response = client().prepareSearch("idx") .addAggregation( filters("tags") - .filter("tag1", termFilter("tag", "tag1")) - .filter("tag2", termFilter("tag", "tag2")) + .filter("tag1", termQuery("tag", "tag1")) + .filter("tag2", termQuery("tag", "tag2")) .subAggregation(avg("avg_value").field("value"))) .execute().actionGet(); @@ -208,8 +208,8 @@ public class FiltersTests extends ElasticsearchIntegrationTest { client().prepareSearch("idx") .addAggregation( filters("tags") - .filter("tag1", termFilter("tag", "tag1")) - .filter("tag2", termFilter("tag", "tag2")) + .filter("tag1", termQuery("tag", "tag1")) + .filter("tag2", termQuery("tag", "tag2")) .subAggregation(avg("avg_value")) ) .execute().actionGet(); @@ -226,7 +226,7 @@ public class FiltersTests extends ElasticsearchIntegrationTest { SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx") .setQuery(matchAllQuery()) .addAggregation(histogram("histo").field("value").interval(1l).minDocCount(0) - .subAggregation(filters("filters").filter("all", matchAllFilter()))) + .subAggregation(filters("filters").filter("all", matchAllQuery()))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(2l)); @@ -248,8 +248,8 @@ public class FiltersTests extends ElasticsearchIntegrationTest { SearchResponse response = client().prepareSearch("idx") .addAggregation( filters("tags") - .filter(termFilter("tag", "tag1")) - .filter(termFilter("tag", "tag2"))) + .filter(termQuery("tag", "tag1")) + .filter(termQuery("tag", "tag2"))) .execute().actionGet(); assertSearchResponse(response); diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/GeoHashGridTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/GeoHashGridTests.java index 2616c133dd4..7a6c2fe9e1c 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/GeoHashGridTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/GeoHashGridTests.java @@ -27,7 +27,7 @@ import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.geo.GeoHashUtils; import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.GeoBoundingBoxFilterBuilder; +import org.elasticsearch.index.query.GeoBoundingBoxQueryBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.filter.Filter; import org.elasticsearch.search.aggregations.bucket.geogrid.GeoHashGrid; @@ -190,8 +190,8 @@ public class GeoHashGridTests extends ElasticsearchIntegrationTest { @Test public void filtered() throws Exception { - GeoBoundingBoxFilterBuilder bbox = new GeoBoundingBoxFilterBuilder("location"); - bbox.topLeft(smallestGeoHash).bottomRight(smallestGeoHash).filterName("bbox"); + GeoBoundingBoxQueryBuilder bbox = new GeoBoundingBoxQueryBuilder("location"); + bbox.topLeft(smallestGeoHash).bottomRight(smallestGeoHash).queryName("bbox"); for (int precision = 1; precision <= highestPrecisionGeohash; precision++) { SearchResponse response = client().prepareSearch("idx") .addAggregation( diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/HistogramTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/HistogramTests.java index 9a6c7c0f9f1..031e4701a69 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/HistogramTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/HistogramTests.java @@ -20,7 +20,6 @@ package org.elasticsearch.search.aggregations.bucket; import com.carrotsearch.hppc.LongOpenHashSet; -import org.apache.tools.ant.filters.TokenFilter.ContainsString; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; @@ -41,7 +40,6 @@ import java.util.Iterator; import java.util.List; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.matchAllFilter; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.search.aggregations.AggregationBuilders.filter; import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram; @@ -563,7 +561,7 @@ public class HistogramTests extends ElasticsearchIntegrationTest { boolean asc = randomBoolean(); SearchResponse response = client().prepareSearch("idx") .addAggregation(histogram("histo").field(SINGLE_VALUED_FIELD_NAME).interval(interval).order(Histogram.Order.aggregation("filter>max", asc)) - .subAggregation(filter("filter").filter(matchAllFilter()) + .subAggregation(filter("filter").filter(matchAllQuery()) .subAggregation(max("max").field(SINGLE_VALUED_FIELD_NAME)))) .execute().actionGet(); diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/LongTermsTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/LongTermsTests.java index 9cf7ce64d7d..9d97dbabd34 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/LongTermsTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/LongTermsTests.java @@ -21,7 +21,7 @@ package org.elasticsearch.search.aggregations.bucket; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.aggregations.Aggregator.SubAggCollectionMode; import org.elasticsearch.search.aggregations.bucket.filter.Filter; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; @@ -893,7 +893,7 @@ public class LongTermsTests extends AbstractTermsTests { .field("num_tag") .collectMode(randomFrom(SubAggCollectionMode.values())) .order(Terms.Order.aggregation("filter", asc)) - .subAggregation(filter("filter").filter(FilterBuilders.matchAllFilter())) + .subAggregation(filter("filter").filter(QueryBuilders.matchAllQuery())) ).execute().actionGet(); @@ -931,8 +931,8 @@ public class LongTermsTests extends AbstractTermsTests { .field("num_tag") .collectMode(randomFrom(SubAggCollectionMode.values())) .order(Terms.Order.aggregation("filter1>filter2>max", asc)) - .subAggregation(filter("filter1").filter(FilterBuilders.matchAllFilter()) - .subAggregation(filter("filter2").filter(FilterBuilders.matchAllFilter()) + .subAggregation(filter("filter1").filter(QueryBuilders.matchAllQuery()) + .subAggregation(filter("filter2").filter(QueryBuilders.matchAllQuery()) .subAggregation(max("max").field(SINGLE_VALUED_FIELD_NAME)))) ).execute().actionGet(); diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/NestedTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/NestedTests.java index d437eb34915..bd3e501146c 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/NestedTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/NestedTests.java @@ -44,8 +44,8 @@ import java.util.List; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.aggregations.AggregationBuilders.filter; import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram; import static org.elasticsearch.search.aggregations.AggregationBuilders.max; @@ -418,7 +418,7 @@ public class NestedTests extends ElasticsearchIntegrationTest { terms("endDate").field("dates.month.end").subAggregation( terms("period").field("dates.month.label").subAggregation( nested("ctxt_idfier_nested").path("comments").subAggregation( - filter("comment_filter").filter(termFilter("comments.identifier", "29111")).subAggregation( + filter("comment_filter").filter(termQuery("comments.identifier", "29111")).subAggregation( nested("nested_tags").path("comments.tags").subAggregation( terms("tag").field("comments.tags.name") ) diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/ReverseNestedTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/ReverseNestedTests.java index 79ff6da729c..dd0853c0bba 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/ReverseNestedTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/ReverseNestedTests.java @@ -18,7 +18,6 @@ */ package org.elasticsearch.search.aggregations.bucket; -import org.apache.lucene.util.LuceneTestCase.AwaitsFix; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.settings.ImmutableSettings; @@ -40,8 +39,8 @@ import java.util.List; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.aggregations.AggregationBuilders.count; import static org.elasticsearch.search.aggregations.AggregationBuilders.filter; import static org.elasticsearch.search.aggregations.AggregationBuilders.nested; @@ -565,7 +564,7 @@ public class ReverseNestedTests extends ElasticsearchIntegrationTest { terms("group_by_category").field("category.name").subAggregation( reverseNested("to_root").subAggregation( nested("nested_1").path("sku").subAggregation( - filter("filter_by_sku").filter(termFilter("sku.sku_type", "bar1")).subAggregation( + filter("filter_by_sku").filter(termQuery("sku.sku_type", "bar1")).subAggregation( count("sku_count").field("sku.sku_type") ) ) @@ -600,9 +599,9 @@ public class ReverseNestedTests extends ElasticsearchIntegrationTest { terms("group_by_category").field("category.name").subAggregation( reverseNested("to_root").subAggregation( nested("nested_1").path("sku").subAggregation( - filter("filter_by_sku").filter(termFilter("sku.sku_type", "bar1")).subAggregation( + filter("filter_by_sku").filter(termQuery("sku.sku_type", "bar1")).subAggregation( nested("nested_2").path("sku.colors").subAggregation( - filter("filter_sku_color").filter(termFilter("sku.colors.name", "red")).subAggregation( + filter("filter_sku_color").filter(termQuery("sku.colors.name", "red")).subAggregation( reverseNested("reverse_to_sku").path("sku").subAggregation( count("sku_count").field("sku.sku_type") ) diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/ShardReduceTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/ShardReduceTests.java index e6b508dc5d9..232f85f3cfb 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/ShardReduceTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/ShardReduceTests.java @@ -21,7 +21,6 @@ package org.elasticsearch.search.aggregations.bucket; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.geo.GeoHashUtils; -import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.aggregations.Aggregator.SubAggCollectionMode; import org.elasticsearch.search.aggregations.bucket.filter.Filter; @@ -110,7 +109,7 @@ public class ShardReduceTests extends ElasticsearchIntegrationTest { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) - .addAggregation(filter("filter").filter(FilterBuilders.matchAllFilter()) + .addAggregation(filter("filter").filter(QueryBuilders.matchAllQuery()) .subAggregation(dateHistogram("histo").field("date").interval(DateHistogramInterval.DAY).minDocCount(0))) .execute().actionGet(); @@ -143,7 +142,7 @@ public class ShardReduceTests extends ElasticsearchIntegrationTest { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(global("global") - .subAggregation(filter("filter").filter(FilterBuilders.matchAllFilter()) + .subAggregation(filter("filter").filter(QueryBuilders.matchAllQuery()) .subAggregation(missing("missing").field("foobar") .subAggregation(dateHistogram("histo").field("date").interval(DateHistogramInterval.DAY).minDocCount(0))))) .execute().actionGet(); diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/SignificantTermsSignificanceScoreTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/SignificantTermsSignificanceScoreTests.java index 14330a1f900..787b7decb91 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/SignificantTermsSignificanceScoreTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/SignificantTermsSignificanceScoreTests.java @@ -28,7 +28,7 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.plugins.AbstractPlugin; import org.elasticsearch.script.ScriptModule; @@ -345,18 +345,18 @@ public class SignificantTermsSignificanceScoreTests extends ElasticsearchIntegra assertSearchResponse(response1); SearchResponse response2 = client().prepareSearch(INDEX_NAME).setTypes(DOC_TYPE) .addAggregation((new FilterAggregationBuilder("0")) - .filter(FilterBuilders.termFilter(CLASS_FIELD, "0")) + .filter(QueryBuilders.termQuery(CLASS_FIELD, "0")) .subAggregation(new SignificantTermsBuilder("sig_terms") .field(TEXT_FIELD) .minDocCount(1) - .backgroundFilter(FilterBuilders.termFilter(CLASS_FIELD, "1")) + .backgroundFilter(QueryBuilders.termQuery(CLASS_FIELD, "1")) .significanceHeuristic(significanceHeuristicExpectingSeparateSets))) .addAggregation((new FilterAggregationBuilder("1")) - .filter(FilterBuilders.termFilter(CLASS_FIELD, "1")) + .filter(QueryBuilders.termQuery(CLASS_FIELD, "1")) .subAggregation(new SignificantTermsBuilder("sig_terms") .field(TEXT_FIELD) .minDocCount(1) - .backgroundFilter(FilterBuilders.termFilter(CLASS_FIELD, "0")) + .backgroundFilter(QueryBuilders.termQuery(CLASS_FIELD, "0")) .significanceHeuristic(significanceHeuristicExpectingSeparateSets))) .execute() .actionGet(); diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/SignificantTermsTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/SignificantTermsTests.java index db2d86c742a..9f993eb9f39 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/SignificantTermsTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/SignificantTermsTests.java @@ -23,7 +23,7 @@ import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.TermQueryBuilder; import org.elasticsearch.search.aggregations.bucket.significant.SignificantTerms; import org.elasticsearch.search.aggregations.bucket.significant.SignificantTerms.Bucket; @@ -301,7 +301,7 @@ public class SignificantTermsTests extends ElasticsearchIntegrationTest { .setQuery(new TermQueryBuilder("_all", "terje")) .setFrom(0).setSize(60).setExplain(true) .addAggregation(new SignificantTermsBuilder("mySignificantTerms").field("description") - .minDocCount(2).backgroundFilter(FilterBuilders.termFilter("fact_category", 1))) + .minDocCount(2).backgroundFilter(QueryBuilders.termQuery("fact_category", 1))) .execute() .actionGet(); assertSearchResponse(response); @@ -327,7 +327,7 @@ public class SignificantTermsTests extends ElasticsearchIntegrationTest { .setQuery(new TermQueryBuilder("_all", "weller")) .setFrom(0).setSize(60).setExplain(true) .addAggregation(new SignificantTermsBuilder("mySignificantTerms").field("description") - .minDocCount(1).backgroundFilter(FilterBuilders.termsFilter("description", "paul"))) + .minDocCount(1).backgroundFilter(QueryBuilders.termsQuery("description", "paul"))) .execute() .actionGet(); assertSearchResponse(response); diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/StringTermsTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/StringTermsTests.java index 3ef59e06a90..12ac7575f13 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/StringTermsTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/StringTermsTests.java @@ -25,7 +25,7 @@ import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.index.mapper.internal.FieldNamesFieldMapper; import org.elasticsearch.index.mapper.internal.IndexFieldMapper; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.aggregations.Aggregator.SubAggCollectionMode; import org.elasticsearch.search.aggregations.bucket.filter.Filter; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; @@ -49,11 +49,10 @@ import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.regex.Pattern; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.aggregations.AggregationBuilders.avg; import static org.elasticsearch.search.aggregations.AggregationBuilders.count; import static org.elasticsearch.search.aggregations.AggregationBuilders.extendedStats; @@ -987,7 +986,7 @@ public class StringTermsTests extends AbstractTermsTests { public void stringTermsNestedIntoPerBucketAggregator() throws Exception { // no execution hint so that the logic that decides whether or not to use ordinals is executed SearchResponse response = client().prepareSearch("idx").setTypes("type") - .addAggregation(filter("filter").filter(termFilter(MULTI_VALUED_FIELD_NAME, "val3")).subAggregation(terms("terms").field(MULTI_VALUED_FIELD_NAME) + .addAggregation(filter("filter").filter(termQuery(MULTI_VALUED_FIELD_NAME, "val3")).subAggregation(terms("terms").field(MULTI_VALUED_FIELD_NAME) .collectMode(randomFrom(SubAggCollectionMode.values())))) .execute().actionGet(); @@ -1069,7 +1068,7 @@ public class StringTermsTests extends AbstractTermsTests { .field("tag") .collectMode(randomFrom(SubAggCollectionMode.values())) .order(Terms.Order.aggregation("filter", asc)) - .subAggregation(filter("filter").filter(FilterBuilders.matchAllFilter())) + .subAggregation(filter("filter").filter(QueryBuilders.matchAllQuery())) ).execute().actionGet(); @@ -1108,8 +1107,8 @@ public class StringTermsTests extends AbstractTermsTests { .field("tag") .collectMode(randomFrom(SubAggCollectionMode.values())) .order(Terms.Order.aggregation("filter1>filter2>stats.max", asc)) - .subAggregation(filter("filter1").filter(FilterBuilders.matchAllFilter()) - .subAggregation(filter("filter2").filter(FilterBuilders.matchAllFilter()) + .subAggregation(filter("filter1").filter(QueryBuilders.matchAllQuery()) + .subAggregation(filter("filter2").filter(QueryBuilders.matchAllQuery()) .subAggregation(stats("stats").field("i")))) ).execute().actionGet(); @@ -1170,8 +1169,8 @@ public class StringTermsTests extends AbstractTermsTests { .field("tag") .collectMode(randomFrom(SubAggCollectionMode.values())) .order(Terms.Order.aggregation("filter1>" + filter2Name + ">" + statsName + ".max", asc)) - .subAggregation(filter("filter1").filter(FilterBuilders.matchAllFilter()) - .subAggregation(filter(filter2Name).filter(FilterBuilders.matchAllFilter()) + .subAggregation(filter("filter1").filter(QueryBuilders.matchAllQuery()) + .subAggregation(filter(filter2Name).filter(QueryBuilders.matchAllQuery()) .subAggregation(stats(statsName).field("i")))) ).execute().actionGet(); @@ -1232,8 +1231,8 @@ public class StringTermsTests extends AbstractTermsTests { .field("tag") .collectMode(randomFrom(SubAggCollectionMode.values())) .order(Terms.Order.aggregation("filter1>" + filter2Name + ">" + statsName + "[max]", asc)) - .subAggregation(filter("filter1").filter(FilterBuilders.matchAllFilter()) - .subAggregation(filter(filter2Name).filter(FilterBuilders.matchAllFilter()) + .subAggregation(filter("filter1").filter(QueryBuilders.matchAllQuery()) + .subAggregation(filter(filter2Name).filter(QueryBuilders.matchAllQuery()) .subAggregation(stats(statsName).field("i")))) ).execute().actionGet(); diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/TermsShardMinDocCountTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/TermsShardMinDocCountTests.java index f75270f2ce7..4a7a49d2e99 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/TermsShardMinDocCountTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/TermsShardMinDocCountTests.java @@ -20,7 +20,7 @@ package org.elasticsearch.search.aggregations.bucket; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.filter.InternalFilter; import org.elasticsearch.search.aggregations.bucket.significant.SignificantTerms; @@ -74,7 +74,7 @@ public class TermsShardMinDocCountTests extends ElasticsearchIntegrationTest { // first, check that indeed when not setting the shardMinDocCount parameter 0 terms are returned SearchResponse response = client().prepareSearch(index) .addAggregation( - (new FilterAggregationBuilder("inclass").filter(FilterBuilders.termFilter("class", true))) + (new FilterAggregationBuilder("inclass").filter(QueryBuilders.termQuery("class", true))) .subAggregation(new SignificantTermsBuilder("mySignificantTerms").field("text").minDocCount(2).size(2).executionHint(randomExecutionHint())) ) .execute() @@ -87,7 +87,7 @@ public class TermsShardMinDocCountTests extends ElasticsearchIntegrationTest { response = client().prepareSearch(index) .addAggregation( - (new FilterAggregationBuilder("inclass").filter(FilterBuilders.termFilter("class", true))) + (new FilterAggregationBuilder("inclass").filter(QueryBuilders.termQuery("class", true))) .subAggregation(new SignificantTermsBuilder("mySignificantTerms").field("text").minDocCount(2).shardMinDocCount(2).size(2).executionHint(randomExecutionHint())) ) .execute() diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/TopHitsTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/TopHitsTests.java index 70bedbdb40f..ba927efd641 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/TopHitsTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/TopHitsTests.java @@ -24,7 +24,7 @@ import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.SearchHits; @@ -337,7 +337,7 @@ public class TopHitsTests extends ElasticsearchIntegrationTest { .setTypes("type") .setFrom(from) .setSize(size) - .setPostFilter(FilterBuilders.termFilter(TERMS_AGGS_FIELD, "val0")) + .setPostFilter(QueryBuilders.termQuery(TERMS_AGGS_FIELD, "val0")) .addSort(SORT_FIELD, SortOrder.DESC) .get(); assertSearchResponse(control); diff --git a/src/test/java/org/elasticsearch/search/aggregations/reducers/moving/avg/MovAvgTests.java b/src/test/java/org/elasticsearch/search/aggregations/reducers/moving/avg/MovAvgTests.java index 9973ee0fc69..3a330b3b9dd 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/reducers/moving/avg/MovAvgTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/reducers/moving/avg/MovAvgTests.java @@ -26,7 +26,7 @@ import org.apache.lucene.util.LuceneTestCase; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.index.query.RangeFilterBuilder; +import org.elasticsearch.index.query.RangeQueryBuilder; import org.elasticsearch.search.aggregations.bucket.filter.InternalFilter; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram; @@ -816,7 +816,7 @@ public class MovAvgTests extends ElasticsearchIntegrationTest { SearchResponse response = client() .prepareSearch("idx").setTypes("gap_type") .addAggregation( - filter("filtered").filter(new RangeFilterBuilder(INTERVAL_FIELD).from(1)).subAggregation( + filter("filtered").filter(new RangeQueryBuilder(INTERVAL_FIELD).from(1)).subAggregation( histogram("histo").field(INTERVAL_FIELD).interval(1).extendedBounds(0L, 49L) .subAggregation(randomMetric("the_metric", GAP_FIELD)) .subAggregation(movingAvg("movavg_values") @@ -859,7 +859,7 @@ public class MovAvgTests extends ElasticsearchIntegrationTest { SearchResponse response = client() .prepareSearch("idx").setTypes("gap_type") .addAggregation( - filter("filtered").filter(new RangeFilterBuilder(INTERVAL_FIELD).from(1)).subAggregation( + filter("filtered").filter(new RangeQueryBuilder(INTERVAL_FIELD).from(1)).subAggregation( histogram("histo").field(INTERVAL_FIELD).interval(1).extendedBounds(0L, 49L) .subAggregation(randomMetric("the_metric", GAP_FIELD)) .subAggregation(movingAvg("movavg_values") @@ -915,7 +915,7 @@ public class MovAvgTests extends ElasticsearchIntegrationTest { SearchResponse response = client() .prepareSearch("idx").setTypes("gap_type") .addAggregation( - filter("filtered").filter(new RangeFilterBuilder(INTERVAL_FIELD).to(1)).subAggregation( + filter("filtered").filter(new RangeQueryBuilder(INTERVAL_FIELD).to(1)).subAggregation( histogram("histo").field(INTERVAL_FIELD).interval(1).extendedBounds(0L, 49L) .subAggregation(randomMetric("the_metric", GAP_FIELD)) .subAggregation(movingAvg("movavg_values") @@ -962,7 +962,7 @@ public class MovAvgTests extends ElasticsearchIntegrationTest { SearchResponse response = client() .prepareSearch("idx").setTypes("gap_type") .addAggregation( - filter("filtered").filter(new RangeFilterBuilder(INTERVAL_FIELD).to(1)).subAggregation( + filter("filtered").filter(new RangeQueryBuilder(INTERVAL_FIELD).to(1)).subAggregation( histogram("histo").field(INTERVAL_FIELD).interval(1).extendedBounds(0L, 49L) .subAggregation(randomMetric("the_metric", GAP_FIELD)) .subAggregation(movingAvg("movavg_values") diff --git a/src/test/java/org/elasticsearch/search/basic/TransportTwoNodesSearchTests.java b/src/test/java/org/elasticsearch/search/basic/TransportTwoNodesSearchTests.java index 2381cd2eea0..988274f515d 100644 --- a/src/test/java/org/elasticsearch/search/basic/TransportTwoNodesSearchTests.java +++ b/src/test/java/org/elasticsearch/search/basic/TransportTwoNodesSearchTests.java @@ -54,7 +54,7 @@ import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.unit.TimeValue.timeValueMinutes; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; @@ -348,8 +348,8 @@ public class TransportTwoNodesSearchTests extends ElasticsearchIntegrationTest { .query(termQuery("multi", "test")) .from(0).size(20).explain(true) .aggregation(AggregationBuilders.global("global").subAggregation( - AggregationBuilders.filter("all").filter(termFilter("multi", "test")))) - .aggregation(AggregationBuilders.filter("test1").filter(termFilter("name", "test1"))); + AggregationBuilders.filter("all").filter(termQuery("multi", "test")))) + .aggregation(AggregationBuilders.filter("test1").filter(termQuery("name", "test1"))); SearchResponse searchResponse = client().search(searchRequest("test").source(sourceBuilder)).actionGet(); assertNoFailures(searchResponse); diff --git a/src/test/java/org/elasticsearch/search/child/SimpleChildQuerySearchTests.java b/src/test/java/org/elasticsearch/search/child/SimpleChildQuerySearchTests.java index 357a19afa60..4e006683fdf 100644 --- a/src/test/java/org/elasticsearch/search/child/SimpleChildQuerySearchTests.java +++ b/src/test/java/org/elasticsearch/search/child/SimpleChildQuerySearchTests.java @@ -19,7 +19,6 @@ package org.elasticsearch.search.child; import org.apache.lucene.util.LuceneTestCase; -import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheResponse; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse; @@ -42,9 +41,6 @@ import org.elasticsearch.index.cache.filter.index.IndexFilterCache; import org.elasticsearch.index.fielddata.FieldDataType; import org.elasticsearch.index.mapper.FieldMapper.Loading; import org.elasticsearch.index.mapper.MergeMappingException; -import org.elasticsearch.index.query.FilterBuilder; -import org.elasticsearch.index.query.FilterBuilders; -import org.elasticsearch.index.query.HasChildFilterBuilder; import org.elasticsearch.index.query.HasChildQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; @@ -76,13 +72,6 @@ import static com.google.common.collect.Maps.newHashMap; import static org.elasticsearch.common.io.Streams.copyToStringFromClasspath; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.boolFilter; -import static org.elasticsearch.index.query.FilterBuilders.hasParentFilter; -import static org.elasticsearch.index.query.FilterBuilders.matchAllFilter; -import static org.elasticsearch.index.query.FilterBuilders.notFilter; -import static org.elasticsearch.index.query.FilterBuilders.queryFilter; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; -import static org.elasticsearch.index.query.FilterBuilders.termsFilter; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; @@ -91,9 +80,11 @@ import static org.elasticsearch.index.query.QueryBuilders.idsQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery; +import static org.elasticsearch.index.query.QueryBuilders.notQuery; import static org.elasticsearch.index.query.QueryBuilders.prefixQuery; import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; +import static org.elasticsearch.index.query.QueryBuilders.termsQuery; import static org.elasticsearch.index.query.QueryBuilders.topChildrenQuery; import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.factorFunction; import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.scriptFunction; @@ -147,23 +138,23 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { .setQuery( filteredQuery( matchAllQuery(), - hasChildFilter( + hasChildQuery( "child", filteredQuery(termQuery("c_field", "c_value1"), - hasChildFilter("grandchild", termQuery("gc_field", "gc_value1")))))).get(); + hasChildQuery("grandchild", termQuery("gc_field", "gc_value1")))))).get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); assertThat(searchResponse.getHits().getAt(0).id(), equalTo("p1")); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), hasParentFilter("parent", termFilter("p_field", "p_value1")))).execute() + .setQuery(filteredQuery(matchAllQuery(), hasParentQuery("parent", termQuery("p_field", "p_value1")))).execute() .actionGet(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); assertThat(searchResponse.getHits().getAt(0).id(), equalTo("c1")); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), hasParentFilter("child", termFilter("c_field", "c_value1")))).execute() + .setQuery(filteredQuery(matchAllQuery(), hasParentQuery("child", termQuery("c_field", "c_value1")))).execute() .actionGet(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); @@ -373,7 +364,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { assertThat(indicesStatsResponse.getTotal().getFieldData().getMemorySizeInBytes(), equalTo(0l)); SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(constantScoreQuery(hasChildFilter("child", termQuery("c_field", "blue")))) + .setQuery(constantScoreQuery(hasChildQuery("child", termQuery("c_field", "blue")))) .get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); @@ -423,15 +414,15 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { for (int i = 1; i <= 10; i++) { logger.info("Round {}", i); SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(constantScoreQuery(queryFilter(topChildrenQuery("child", matchAllQuery())))).execute() + .setQuery(constantScoreQuery(topChildrenQuery("child", matchAllQuery()))).execute() .actionGet(); assertNoFailures(searchResponse); searchResponse = client().prepareSearch("test") - .setQuery(constantScoreQuery(queryFilter(hasChildQuery("child", matchAllQuery()).scoreType("max")))) + .setQuery(constantScoreQuery(hasChildQuery("child", matchAllQuery()).scoreType("max"))) .get(); assertNoFailures(searchResponse); searchResponse = client().prepareSearch("test") - .setQuery(constantScoreQuery(queryFilter(hasParentQuery("parent", matchAllQuery()).scoreType("score")))) + .setQuery(constantScoreQuery(hasParentQuery("parent", matchAllQuery()).scoreType("score"))) .get(); assertNoFailures(searchResponse); } @@ -473,7 +464,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { assertThat(parentToChildren.isEmpty(), equalTo(false)); for (Map.Entry> parentToChildrenEntry : parentToChildren.entrySet()) { SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(constantScoreQuery(hasParentFilter("parent", termQuery("p_field", parentToChildrenEntry.getKey())))) + .setQuery(constantScoreQuery(hasParentQuery("parent", termQuery("p_field", parentToChildrenEntry.getKey())))) .setSize(numChildDocsPerParent).get(); assertNoFailures(searchResponse); @@ -554,18 +545,18 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { // HAS CHILD FILTER searchResponse = client().prepareSearch("test") - .setQuery(constantScoreQuery(hasChildFilter("child", termQuery("c_field", "yellow")))).get(); + .setQuery(constantScoreQuery(hasChildQuery("child", termQuery("c_field", "yellow")))).get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); assertThat(searchResponse.getHits().getAt(0).id(), equalTo("p1")); - searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(hasChildFilter("child", termQuery("c_field", "blue")))) + searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(hasChildQuery("child", termQuery("c_field", "blue")))) .get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); assertThat(searchResponse.getHits().getAt(0).id(), equalTo("p2")); - searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(hasChildFilter("child", termQuery("c_field", "red")))) + searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(hasChildQuery("child", termQuery("c_field", "red")))) .get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(2l)); @@ -594,7 +585,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { .prepareSearch("test") .setQuery(topChildrenQuery("child", boolQuery().should(termQuery("c_field", "red")).should(termQuery("c_field", "yellow")))) .addAggregation(AggregationBuilders.global("global").subAggregation( - AggregationBuilders.filter("filter").filter(boolFilter().should(termFilter("c_field", "red")).should(termFilter("c_field", "yellow"))).subAggregation( + AggregationBuilders.filter("filter").filter(boolQuery().should(termQuery("c_field", "red")).should(termQuery("c_field", "yellow"))).subAggregation( AggregationBuilders.terms("facet1").field("c_field")))).get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(2l)); @@ -637,7 +628,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { assertThat(searchResponse.getHits().getAt(0).sourceAsString(), containsString("\"p_value1\"")); searchResponse = client().prepareSearch("test") - .setQuery(constantScoreQuery(hasChildFilter("child", termQuery("c_field", "yellow")))).get(); + .setQuery(constantScoreQuery(hasChildQuery("child", termQuery("c_field", "yellow")))).get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); assertThat(searchResponse.getHits().getAt(0).id(), equalTo("p1")); @@ -656,7 +647,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { assertThat(searchResponse.getHits().getAt(0).sourceAsString(), containsString("\"p_value1_updated\"")); searchResponse = client().prepareSearch("test") - .setQuery(constantScoreQuery(hasChildFilter("child", termQuery("c_field", "yellow")))).get(); + .setQuery(constantScoreQuery(hasChildQuery("child", termQuery("c_field", "yellow")))).get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); assertThat(searchResponse.getHits().getAt(0).id(), equalTo("p1")); @@ -768,12 +759,12 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { client().admin().indices().prepareFlush("test").get(); SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), hasChildFilter("child", matchAllQuery()))).get(); + .setQuery(filteredQuery(matchAllQuery(), hasChildQuery("child", matchAllQuery()))).get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), hasParentFilter("parent", matchAllQuery()))).get(); + .setQuery(filteredQuery(matchAllQuery(), hasParentQuery("parent", matchAllQuery()))).get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); } @@ -802,11 +793,11 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { .get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount("test").setQuery(constantScoreQuery(hasChildFilter("child", termQuery("c_field", "1")))) + countResponse = client().prepareCount("test").setQuery(constantScoreQuery(hasChildQuery("child", termQuery("c_field", "1")))) .get(); assertHitCount(countResponse, 1l); - countResponse = client().prepareCount("test").setQuery(constantScoreQuery(hasParentFilter("parent", termQuery("p_field", "1")))) + countResponse = client().prepareCount("test").setQuery(constantScoreQuery(hasParentQuery("parent", termQuery("p_field", "1")))) .get(); assertHitCount(countResponse, 1l); } @@ -1041,13 +1032,13 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { client().admin().indices().prepareFlush("test").get(); SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), hasChildFilter("child", termFilter("c_field", 1)))).get(); + .setQuery(filteredQuery(matchAllQuery(), hasChildQuery("child", termQuery("c_field", 1)))).get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits()[0].id(), equalTo("1")); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), hasParentFilter("parent", termFilter("p_field", 1)))).get(); + .setQuery(filteredQuery(matchAllQuery(), hasParentQuery("parent", termQuery("p_field", 1)))).get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits()[0].id(), equalTo("2")); @@ -1067,27 +1058,27 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { refresh(); SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), queryFilter(hasChildQuery("child", matchQuery("c_field", 1))))).get(); + .setQuery(filteredQuery(matchAllQuery(), hasChildQuery("child", matchQuery("c_field", 1)))).get(); assertSearchHit(searchResponse, 1, hasId("1")); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), queryFilter(topChildrenQuery("child", matchQuery("c_field", 1))))).get(); + .setQuery(filteredQuery(matchAllQuery(), topChildrenQuery("child", matchQuery("c_field", 1)))).get(); assertSearchHit(searchResponse, 1, hasId("1")); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), queryFilter(hasParentQuery("parent", matchQuery("p_field", 1))))).get(); + .setQuery(filteredQuery(matchAllQuery(), hasParentQuery("parent", matchQuery("p_field", 1)))).get(); assertSearchHit(searchResponse, 1, hasId("2")); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), queryFilter(boolQuery().must(hasChildQuery("child", matchQuery("c_field", 1)))))).get(); + .setQuery(filteredQuery(matchAllQuery(), boolQuery().must(hasChildQuery("child", matchQuery("c_field", 1))))).get(); assertSearchHit(searchResponse, 1, hasId("1")); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), queryFilter(boolQuery().must(topChildrenQuery("child", matchQuery("c_field", 1)))))).get(); + .setQuery(filteredQuery(matchAllQuery(), boolQuery().must(topChildrenQuery("child", matchQuery("c_field", 1))))).get(); assertSearchHit(searchResponse, 1, hasId("1")); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), queryFilter(boolQuery().must(hasParentQuery("parent", matchQuery("p_field", 1)))))).get(); + .setQuery(filteredQuery(matchAllQuery(), boolQuery().must(hasParentQuery("parent", matchQuery("p_field", 1))))).get(); assertSearchHit(searchResponse, 1, hasId("2")); } @@ -1254,7 +1245,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { ensureGreen(); // test term filter - SearchResponse response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termFilter("_parent", "p1"))) + SearchResponse response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termQuery("_parent", "p1"))) .get(); assertHitCount(response, 0l); @@ -1262,51 +1253,51 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "parent", "p1").setSource("p_field", "value").get(); client().prepareIndex("test", "child", "c1").setSource("c_field", "value").setParent("p1").get(); - response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termFilter("_parent", "p1"))).execute() + response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termQuery("_parent", "p1"))).execute() .actionGet(); assertHitCount(response, 0l); refresh(); - response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termFilter("_parent", "p1"))).execute() + response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termQuery("_parent", "p1"))).execute() .actionGet(); assertHitCount(response, 1l); - response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termFilter("_parent", "parent#p1"))).execute() + response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termQuery("_parent", "parent#p1"))).execute() .actionGet(); assertHitCount(response, 1l); client().prepareIndex("test", "parent2", "p1").setSource("p_field", "value").setRefresh(true).get(); - response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termFilter("_parent", "p1"))).execute() + response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termQuery("_parent", "p1"))).execute() .actionGet(); assertHitCount(response, 1l); - response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termFilter("_parent", "parent#p1"))).execute() + response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termQuery("_parent", "parent#p1"))).execute() .actionGet(); assertHitCount(response, 1l); // test terms filter client().prepareIndex("test", "child2", "c1").setSource("c_field", "value").setParent("p1").get(); - response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("_parent", "p1"))).execute() + response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("_parent", "p1"))).execute() .actionGet(); assertHitCount(response, 1l); - response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("_parent", "parent#p1"))).execute() + response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("_parent", "parent#p1"))).execute() .actionGet(); assertHitCount(response, 1l); refresh(); - response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("_parent", "p1"))).execute() + response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("_parent", "p1"))).execute() .actionGet(); assertHitCount(response, 2l); refresh(); - response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("_parent", "p1", "p1"))).execute() + response = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("_parent", "p1", "p1"))).execute() .actionGet(); assertHitCount(response, 2l); response = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("_parent", "parent#p1", "parent2#p1"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("_parent", "parent#p1", "parent2#p1"))).get(); assertHitCount(response, 2l); } @@ -1333,7 +1324,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { client().admin().indices().prepareRefresh("test").get(); SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(constantScoreQuery(hasChildFilter("child", termQuery("c_field", "blue")).cache(true))) + .setQuery(constantScoreQuery(hasChildQuery("child", termQuery("c_field", "blue")))) .get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); @@ -1342,7 +1333,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { client().admin().indices().prepareRefresh("test").get(); searchResponse = client().prepareSearch("test") - .setQuery(constantScoreQuery(hasChildFilter("child", termQuery("c_field", "blue")).cache(true))) + .setQuery(constantScoreQuery(hasChildQuery("child", termQuery("c_field", "blue")))) .get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(2l)); @@ -1351,9 +1342,9 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { private QueryBuilder randomHasChild(String type, String field, String value) { if (randomBoolean()) { if (randomBoolean()) { - return constantScoreQuery(hasChildFilter(type, termQuery(field, value))); + return constantScoreQuery(hasChildQuery(type, termQuery(field, value))); } else { - return filteredQuery(matchAllQuery(), hasChildFilter(type, termQuery(field, value))); + return filteredQuery(matchAllQuery(), hasChildQuery(type, termQuery(field, value))); } } else { return hasChildQuery(type, termQuery(field, value)); @@ -1363,9 +1354,9 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { private QueryBuilder randomHasParent(String type, String field, String value) { if (randomBoolean()) { if (randomBoolean()) { - return constantScoreQuery(hasParentFilter(type, termQuery(field, value))); + return constantScoreQuery(hasParentQuery(type, termQuery(field, value))); } else { - return filteredQuery(matchAllQuery(), hasParentFilter(type, termQuery(field, value))); + return filteredQuery(matchAllQuery(), hasParentQuery(type, termQuery(field, value))); } } else { return hasParentQuery(type, termQuery(field, value)); @@ -1558,13 +1549,13 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { String scoreMode = ScoreType.values()[getRandom().nextInt(ScoreType.values().length)].name().toLowerCase(Locale.ROOT); SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(QueryBuilders.hasChildQuery("child", termQuery("c_field", "blue")).scoreType(scoreMode), notFilter(termFilter("p_field", "3")))) + .setQuery(filteredQuery(QueryBuilders.hasChildQuery("child", termQuery("c_field", "blue")).scoreType(scoreMode), notQuery(termQuery("p_field", "3")))) .get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(QueryBuilders.hasChildQuery("child", termQuery("c_field", "red")).scoreType(scoreMode), notFilter(termFilter("p_field", "3")))) + .setQuery(filteredQuery(QueryBuilders.hasChildQuery("child", termQuery("c_field", "red")).scoreType(scoreMode), notQuery(termQuery("p_field", "3")))) .get(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().totalHits(), equalTo(2l)); @@ -1584,6 +1575,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { SearchResponse searchResponse = client().prepareSearch("test").setQuery(topChildrenQuery("child", termQuery("c_field", "1")).queryName("test")) .get(); + System.out.println(searchResponse); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getMatchedQueries().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).getMatchedQueries()[0], equalTo("test")); @@ -1600,13 +1592,13 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { assertThat(searchResponse.getHits().getAt(0).getMatchedQueries().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).getMatchedQueries()[0], equalTo("test")); - searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(hasChildFilter("child", termQuery("c_field", "1")).filterName("test"))) + searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(hasChildQuery("child", termQuery("c_field", "1")).queryName("test"))) .get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getMatchedQueries().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).getMatchedQueries()[0], equalTo("test")); - searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(hasParentFilter("parent", termQuery("p_field", "1")).filterName("test"))) + searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(hasParentQuery("parent", termQuery("p_field", "1")).queryName("test"))) .get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getMatchedQueries().length, equalTo(1)); @@ -1645,7 +1637,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { try { client().prepareSearch("test") - .setPostFilter(hasChildFilter("child", termQuery("c_field", "1"))) + .setPostFilter(hasChildQuery("child", termQuery("c_field", "1"))) .get(); fail(); } catch (SearchPhaseExecutionException e) { @@ -1672,7 +1664,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { try { client().prepareSearch("test") - .setPostFilter(hasParentFilter("parent", termQuery("p_field", "1"))) + .setPostFilter(hasParentQuery("parent", termQuery("p_field", "1"))) .get(); fail(); } catch (SearchPhaseExecutionException e) { @@ -1713,7 +1705,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { searchResponse = client().prepareSearch("test") - .setPostFilter(hasChildFilter("child", termQuery("c_field", "1"))) + .setPostFilter(hasChildQuery("child", termQuery("c_field", "1"))) .get(); assertHitCount(searchResponse, 1l); assertSearchHits(searchResponse, parentId); @@ -1725,7 +1717,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { assertSearchHits(searchResponse, parentId); searchResponse = client().prepareSearch("test") - .setPostFilter(hasParentFilter("parent", termQuery("p_field", "1"))) + .setPostFilter(hasParentQuery("parent", termQuery("p_field", "1"))) .get(); assertHitCount(searchResponse, 1l); assertSearchHits(searchResponse, "c1"); @@ -1766,9 +1758,9 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { for (int i = 0; i < 2; i++) { SearchResponse searchResponse = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), boolFilter() - .must(FilterBuilders.hasChildFilter("child", matchQuery("c_field", "red"))) - .must(matchAllFilter()))) + .setQuery(filteredQuery(matchAllQuery(), boolQuery() + .must(QueryBuilders.hasChildQuery("child", matchQuery("c_field", "red"))) + .must(matchAllQuery()))) .get(); assertThat(searchResponse.getHits().totalHits(), equalTo(2l)); } @@ -1778,9 +1770,9 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { client().admin().indices().prepareRefresh("test").get(); SearchResponse searchResponse = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), boolFilter() - .must(FilterBuilders.hasChildFilter("child", matchQuery("c_field", "red"))) - .must(matchAllFilter()))) + .setQuery(filteredQuery(matchAllQuery(), boolQuery() + .must(QueryBuilders.hasChildQuery("child", matchQuery("c_field", "red"))) + .must(matchAllQuery()))) .get(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); @@ -1801,9 +1793,9 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { QueryBuilder[] queries = new QueryBuilder[]{ hasChildQuery("child", matchAllQuery()), - filteredQuery(matchAllQuery(), hasChildFilter("child", matchAllQuery())), + filteredQuery(matchAllQuery(), hasChildQuery("child", matchAllQuery())), hasParentQuery("parent", matchAllQuery()), - filteredQuery(matchAllQuery(), hasParentFilter("parent", matchAllQuery())), + filteredQuery(matchAllQuery(), hasParentQuery("parent", matchAllQuery())), topChildrenQuery("child", matchAllQuery()).factor(10) }; @@ -1890,22 +1882,22 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { indexRandom(true, indexRequests); SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(constantScoreQuery(hasParentFilter("parent", notFilter(termFilter("field1", "a"))))) + .setQuery(constantScoreQuery(hasParentQuery("parent", notQuery(termQuery("field1", "a"))))) .get(); assertHitCount(searchResponse, 0l); searchResponse = client().prepareSearch("test") - .setQuery(hasParentQuery("parent", constantScoreQuery(notFilter(termFilter("field1", "a"))))) + .setQuery(hasParentQuery("parent", constantScoreQuery(notQuery(termQuery("field1", "a"))))) .get(); assertHitCount(searchResponse, 0l); searchResponse = client().prepareSearch("test") - .setQuery(constantScoreQuery(hasParentFilter("parent", termFilter("field1", "a")))) + .setQuery(constantScoreQuery(hasParentQuery("parent", termQuery("field1", "a")))) .get(); assertHitCount(searchResponse, 2l); searchResponse = client().prepareSearch("test") - .setQuery(hasParentQuery("parent", constantScoreQuery(termFilter("field1", "a")))) + .setQuery(hasParentQuery("parent", constantScoreQuery(termQuery("field1", "a")))) .get(); assertHitCount(searchResponse, 2l); } @@ -1954,10 +1946,10 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { QueryBuilders .hasChildQuery( "child", - QueryBuilders.functionScoreQuery(constantScoreQuery(FilterBuilders.termFilter("foo", "two"))).boostMode("replace").scoreMode("sum") - .add(FilterBuilders.matchAllFilter(), factorFunction(1)) - .add(FilterBuilders.termFilter("foo", "three"), factorFunction(1)) - .add(FilterBuilders.termFilter("foo", "four"), factorFunction(1))).scoreType(scoreType) + QueryBuilders.functionScoreQuery(constantScoreQuery(QueryBuilders.termQuery("foo", "two"))).boostMode("replace").scoreMode("sum") + .add(QueryBuilders.matchAllQuery(), factorFunction(1)) + .add(QueryBuilders.termQuery("foo", "three"), factorFunction(1)) + .add(QueryBuilders.termQuery("foo", "four"), factorFunction(1))).scoreType(scoreType) .minChildren(minChildren).maxChildren(maxChildren).setShortCircuitCutoff(cutoff)) .addSort("_score", SortOrder.DESC).addSort("id", SortOrder.ASC).get(); } @@ -1966,7 +1958,7 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { return client() .prepareSearch("test") .setQuery( - QueryBuilders.constantScoreQuery(FilterBuilders.hasChildFilter("child", termFilter("foo", "two")) + QueryBuilders.constantScoreQuery(QueryBuilders.hasChildQuery("child", termQuery("foo", "two")) .minChildren(minChildren).maxChildren(maxChildren).setShortCircuitCutoff(cutoff))) .addSort("id", SortOrder.ASC).setTrackScores(true).get(); } @@ -2407,30 +2399,18 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { try { client().prepareSearch("test") - .setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.hasChildFilter("child", matchAllQuery()))) + .setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.hasChildQuery("child", matchAllQuery()))) .get(); fail(); } catch (SearchPhaseExecutionException e) { } response = client().prepareSearch("test") - .setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.hasParentFilter("parent", matchAllQuery()))) + .setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.hasParentQuery("parent", matchAllQuery()))) .get(); assertHitCount(response, 0); } - private static HasChildFilterBuilder hasChildFilter(String type, QueryBuilder queryBuilder) { - HasChildFilterBuilder hasChildFilterBuilder = FilterBuilders.hasChildFilter(type, queryBuilder); - hasChildFilterBuilder.setShortCircuitCutoff(randomInt(10)); - return hasChildFilterBuilder; - } - - private static HasChildFilterBuilder hasChildFilter(String type, FilterBuilder filterBuilder) { - HasChildFilterBuilder hasChildFilterBuilder = FilterBuilders.hasChildFilter(type, filterBuilder); - hasChildFilterBuilder.setShortCircuitCutoff(randomInt(10)); - return hasChildFilterBuilder; - } - private static HasChildQueryBuilder hasChildQuery(String type, QueryBuilder queryBuilder) { HasChildQueryBuilder hasChildQueryBuilder = QueryBuilders.hasChildQuery(type, queryBuilder); hasChildQueryBuilder.setShortCircuitCutoff(randomInt(10)); diff --git a/src/test/java/org/elasticsearch/search/fetch/innerhits/NestedChildrenFilterTest.java b/src/test/java/org/elasticsearch/search/fetch/innerhits/NestedChildrenFilterTest.java index 5bf2a8a38d6..72fae268029 100644 --- a/src/test/java/org/elasticsearch/search/fetch/innerhits/NestedChildrenFilterTest.java +++ b/src/test/java/org/elasticsearch/search/fetch/innerhits/NestedChildrenFilterTest.java @@ -86,7 +86,7 @@ public class NestedChildrenFilterTest extends ElasticsearchTestCase { DocIdSetIterator parents = parentFilter.getDocIdSet(leaf).iterator(); for (int parentDoc = parents.nextDoc(); parentDoc != DocIdSetIterator.NO_MORE_DOCS ; parentDoc = parents.nextDoc()) { int expectedChildDocs = leaf.reader().document(parentDoc).getField("num_child_docs").numericValue().intValue(); - hitContext.reset(null, leaf, parentDoc, reader); + hitContext.reset(null, leaf, parentDoc, searcher); NestedChildrenFilter nestedChildrenFilter = new NestedChildrenFilter(parentFilter, childFilter, hitContext); TotalHitCountCollector totalHitCountCollector = new TotalHitCountCollector(); searcher.search(new ConstantScoreQuery(nestedChildrenFilter), totalHitCountCollector); diff --git a/src/test/java/org/elasticsearch/search/functionscore/DecayFunctionScoreTests.java b/src/test/java/org/elasticsearch/search/functionscore/DecayFunctionScoreTests.java index bd6052289c6..8ea20a47dcf 100644 --- a/src/test/java/org/elasticsearch/search/functionscore/DecayFunctionScoreTests.java +++ b/src/test/java/org/elasticsearch/search/functionscore/DecayFunctionScoreTests.java @@ -28,8 +28,7 @@ import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.lucene.search.function.CombineFunction; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.FilterBuilders; -import org.elasticsearch.index.query.MatchAllFilterBuilder; +import org.elasticsearch.index.query.MatchAllQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.functionscore.DecayFunctionBuilder; import org.elasticsearch.index.query.functionscore.gauss.GaussDecayFunctionBuilder; @@ -46,11 +45,23 @@ import java.util.concurrent.ExecutionException; import static org.elasticsearch.client.Requests.indexRequest; import static org.elasticsearch.client.Requests.searchRequest; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; +import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; +import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.exponentialDecayFunction; +import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.gaussDecayFunction; +import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.linearDecayFunction; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; -import static org.hamcrest.Matchers.*; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertOrderedSearchHits; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits; +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.closeTo; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.isOneOf; +import static org.hamcrest.Matchers.lessThan; public class DecayFunctionScoreTests extends ElasticsearchIntegrationTest { @@ -601,9 +612,9 @@ public class DecayFunctionScoreTests extends ElasticsearchIntegrationTest { searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource().size(numDocs).query( functionScoreQuery(termQuery("test", "value")) - .add(new MatchAllFilterBuilder(), linearDecayFunction("date", "2013-05-30", "+15d")) - .add(new MatchAllFilterBuilder(), linearDecayFunction("geo", lonlat, "1000km")) - .add(new MatchAllFilterBuilder(), linearDecayFunction("num", numDocs, numDocs / 2.0)) + .add(new MatchAllQueryBuilder(), linearDecayFunction("date", "2013-05-30", "+15d")) + .add(new MatchAllQueryBuilder(), linearDecayFunction("geo", lonlat, "1000km")) + .add(new MatchAllQueryBuilder(), linearDecayFunction("num", numDocs, numDocs / 2.0)) .scoreMode("multiply").boostMode(CombineFunction.REPLACE.getName())))); SearchResponse sr = response.actionGet(); @@ -639,7 +650,7 @@ public class DecayFunctionScoreTests extends ElasticsearchIntegrationTest { searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource() .size(numDocs) - .query(functionScoreQuery(termQuery("test", "value")).add(new MatchAllFilterBuilder(), + .query(functionScoreQuery(termQuery("test", "value")).add(new MatchAllQueryBuilder(), linearDecayFunction("type1.geo", lonlat, "1000km")).scoreMode("multiply")))); SearchResponse sr = response.actionGet(); @@ -660,7 +671,7 @@ public class DecayFunctionScoreTests extends ElasticsearchIntegrationTest { ActionFuture response = client().search( searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource().query( - functionScoreQuery(termQuery("test", "value")).add(new MatchAllFilterBuilder(), + functionScoreQuery(termQuery("test", "value")).add(new MatchAllQueryBuilder(), linearDecayFunction("num", 1.0, 0.5)).scoreMode("multiply")))); response.actionGet(); } @@ -680,7 +691,7 @@ public class DecayFunctionScoreTests extends ElasticsearchIntegrationTest { ActionFuture response = client().search( searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource().query( - functionScoreQuery().add(new MatchAllFilterBuilder(), linearDecayFunction("num", 1, 0.5)).scoreMode( + functionScoreQuery().add(new MatchAllQueryBuilder(), linearDecayFunction("num", 1, 0.5)).scoreMode( "multiply")))); response.actionGet(); } @@ -911,12 +922,12 @@ public class DecayFunctionScoreTests extends ElasticsearchIntegrationTest { // next test java client try { - client().prepareSearch("t").setQuery(QueryBuilders.functionScoreQuery(FilterBuilders.matchAllFilter(), null)).get(); + client().prepareSearch("t").setQuery(QueryBuilders.functionScoreQuery(QueryBuilders.matchAllQuery(), null)).get(); } catch (IllegalArgumentException failure) { assertTrue(failure.toString().contains("function must not be null")); } try { - client().prepareSearch("t").setQuery(QueryBuilders.functionScoreQuery().add(FilterBuilders.matchAllFilter(), null)).get(); + client().prepareSearch("t").setQuery(QueryBuilders.functionScoreQuery().add(QueryBuilders.matchAllQuery(), null)).get(); } catch (IllegalArgumentException failure) { assertTrue(failure.toString().contains("function must not be null")); } diff --git a/src/test/java/org/elasticsearch/search/functionscore/ExplainableScriptTests.java b/src/test/java/org/elasticsearch/search/functionscore/ExplainableScriptTests.java index 16e4c09d8be..4f30b5aab8b 100644 --- a/src/test/java/org/elasticsearch/search/functionscore/ExplainableScriptTests.java +++ b/src/test/java/org/elasticsearch/search/functionscore/ExplainableScriptTests.java @@ -49,7 +49,6 @@ import java.util.concurrent.ExecutionException; import static org.elasticsearch.client.Requests.searchRequest; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.scriptFunction; diff --git a/src/test/java/org/elasticsearch/search/functionscore/FunctionScoreBackwardCompatibilityTests.java b/src/test/java/org/elasticsearch/search/functionscore/FunctionScoreBackwardCompatibilityTests.java index 6b29f6ff752..79fb834c78d 100644 --- a/src/test/java/org/elasticsearch/search/functionscore/FunctionScoreBackwardCompatibilityTests.java +++ b/src/test/java/org/elasticsearch/search/functionscore/FunctionScoreBackwardCompatibilityTests.java @@ -34,7 +34,7 @@ import java.util.concurrent.ExecutionException; import static org.elasticsearch.client.Requests.searchRequest; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.*; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; @@ -111,10 +111,10 @@ public class FunctionScoreBackwardCompatibilityTests extends ElasticsearchBackwa SearchResponse response = client().search( searchRequest().source( searchSource().query( - functionScoreQuery(termFilter("text", "value")) + functionScoreQuery(termQuery("text", "value")) .add(gaussDecayFunction("loc", new GeoPoint(10, 20), "1000km")) .add(scriptFunction("_index['text']['value'].tf()")) - .add(termFilter("text", "boosted"), factorFunction(5)) + .add(termQuery("text", "boosted"), factorFunction(5)) ))).actionGet(); assertSearchResponse(response); assertOrderedSearchHits(response, ids); diff --git a/src/test/java/org/elasticsearch/search/functionscore/FunctionScoreTests.java b/src/test/java/org/elasticsearch/search/functionscore/FunctionScoreTests.java index 13f95320993..45b7e384a6d 100644 --- a/src/test/java/org/elasticsearch/search/functionscore/FunctionScoreTests.java +++ b/src/test/java/org/elasticsearch/search/functionscore/FunctionScoreTests.java @@ -30,7 +30,6 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder; import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder; import org.elasticsearch.index.query.functionscore.weight.WeightBuilder; -import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.junit.Test; @@ -42,7 +41,7 @@ import java.util.concurrent.ExecutionException; import static org.elasticsearch.client.Requests.searchRequest; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; +import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.exponentialDecayFunction; @@ -172,19 +171,19 @@ public class FunctionScoreTests extends ElasticsearchIntegrationTest { SearchResponse responseWithWeights = client().search( searchRequest().source( searchSource().query( - functionScoreQuery(termFilter(TEXT_FIELD, "value")) + functionScoreQuery(constantScoreQuery(termQuery(TEXT_FIELD, "value"))) .add(gaussDecayFunction(GEO_POINT_FIELD, new GeoPoint(10, 20), "1000km")) .add(fieldValueFactorFunction(DOUBLE_FIELD).modifier(FieldValueFactorFunction.Modifier.LN).setWeight(2)) .add(scriptFunction("_index['" + TEXT_FIELD + "']['value'].tf()").setWeight(3)) ).explain(true))).actionGet(); assertThat(responseWithWeights.getHits().getAt(0).getExplanation().toString(), - equalTo("6.0 = function score, product of:\n 1.0 = ConstantScore(text_field:value), product of:\n 1.0 = boost\n 1.0 = queryNorm\n 6.0 = min of:\n 6.0 = function score, score mode [multiply]\n 1.0 = function score, product of:\n 1.0 = match filter: QueryWrapperFilter(*:*)\n 1.0 = Function for field geo_point_field:\n 1.0 = exp(-0.5*pow(MIN of: [Math.max(arcDistance([10.0, 20.0](=doc value),[10.0, 20.0](=origin)) - 0.0(=offset), 0)],2.0)/7.213475204444817E11)\n 2.0 = function score, product of:\n 1.0 = match filter: QueryWrapperFilter(*:*)\n 2.0 = product of:\n 1.0 = field value function: ln(doc['double_field'].value * factor=1.0)\n 2.0 = weight\n 3.0 = function score, product of:\n 1.0 = match filter: QueryWrapperFilter(*:*)\n 3.0 = product of:\n 1.0 = script score function, computed with script:\"_index['text_field']['value'].tf()\n 1.0 = _score: \n 1.0 = ConstantScore(text_field:value), product of:\n 1.0 = boost\n 1.0 = queryNorm\n 3.0 = weight\n 3.4028235E38 = maxBoost\n 1.0 = queryBoost\n") + equalTo("6.0 = function score, product of:\n 1.0 = ConstantScore(text_field:value), product of:\n 1.0 = boost\n 1.0 = queryNorm\n 6.0 = min of:\n 6.0 = function score, score mode [multiply]\n 1.0 = function score, product of:\n 1.0 = match filter: *:*\n 1.0 = Function for field geo_point_field:\n 1.0 = exp(-0.5*pow(MIN of: [Math.max(arcDistance([10.0, 20.0](=doc value),[10.0, 20.0](=origin)) - 0.0(=offset), 0)],2.0)/7.213475204444817E11)\n 2.0 = function score, product of:\n 1.0 = match filter: *:*\n 2.0 = product of:\n 1.0 = field value function: ln(doc['double_field'].value * factor=1.0)\n 2.0 = weight\n 3.0 = function score, product of:\n 1.0 = match filter: *:*\n 3.0 = product of:\n 1.0 = script score function, computed with script:\"_index['text_field']['value'].tf()\n 1.0 = _score: \n 1.0 = ConstantScore(text_field:value), product of:\n 1.0 = boost\n 1.0 = queryNorm\n 3.0 = weight\n 3.4028235E38 = maxBoost\n 1.0 = queryBoost\n") ); responseWithWeights = client().search( searchRequest().source( searchSource().query( - functionScoreQuery(termFilter(TEXT_FIELD, "value")) + functionScoreQuery(constantScoreQuery(termQuery(TEXT_FIELD, "value"))) .add(weightFactorFunction(4.0f)) ).explain(true))).actionGet(); assertThat(responseWithWeights.getHits().getAt(0).getExplanation().toString(), @@ -205,7 +204,7 @@ public class FunctionScoreTests extends ElasticsearchIntegrationTest { SearchResponse response = client().search( searchRequest().source( searchSource().query( - functionScoreQuery(termFilter(TEXT_FIELD, "value")) + functionScoreQuery(constantScoreQuery(termQuery(TEXT_FIELD, "value"))) .add(gaussDecayFunction(GEO_POINT_FIELD, new GeoPoint(10, 20), "1000km")) .add(fieldValueFactorFunction(DOUBLE_FIELD).modifier(FieldValueFactorFunction.Modifier.LN)) .add(scriptFunction("_index['" + TEXT_FIELD + "']['value'].tf()")) @@ -213,7 +212,7 @@ public class FunctionScoreTests extends ElasticsearchIntegrationTest { SearchResponse responseWithWeights = client().search( searchRequest().source( searchSource().query( - functionScoreQuery(termFilter(TEXT_FIELD, "value")) + functionScoreQuery(constantScoreQuery(termQuery(TEXT_FIELD, "value"))) .add(gaussDecayFunction(GEO_POINT_FIELD, new GeoPoint(10, 20), "1000km").setWeight(2)) .add(fieldValueFactorFunction(DOUBLE_FIELD).modifier(FieldValueFactorFunction.Modifier.LN).setWeight(2)) .add(scriptFunction("_index['" + TEXT_FIELD + "']['value'].tf()").setWeight(2)) @@ -239,7 +238,7 @@ public class FunctionScoreTests extends ElasticsearchIntegrationTest { float[] scores = getScores(scoreFunctionBuilders); String scoreMode = getRandomScoreMode(); - FunctionScoreQueryBuilder withWeights = functionScoreQuery(termFilter(TEXT_FIELD, "value")).scoreMode(scoreMode); + FunctionScoreQueryBuilder withWeights = functionScoreQuery(constantScoreQuery(termQuery(TEXT_FIELD, "value"))).scoreMode(scoreMode); int weightscounter = 0; for (ScoreFunctionBuilder builder : scoreFunctionBuilders) { withWeights.add(builder.setWeight(weights[weightscounter])); @@ -311,7 +310,7 @@ public class FunctionScoreTests extends ElasticsearchIntegrationTest { ScoreFunctionBuilder scoreFunctionBuilder = scoreFunctionBuilders[randomInt(3)]; float[] weights = createRandomWeights(1); float[] scores = getScores(scoreFunctionBuilder); - FunctionScoreQueryBuilder withWeights = functionScoreQuery(termFilter(TEXT_FIELD, "value")); + FunctionScoreQueryBuilder withWeights = functionScoreQuery(constantScoreQuery(termQuery(TEXT_FIELD, "value"))); withWeights.add(scoreFunctionBuilder.setWeight(weights[0])); SearchResponse responseWithWeights = client().search( @@ -334,7 +333,7 @@ public class FunctionScoreTests extends ElasticsearchIntegrationTest { SearchResponse response = client().search( searchRequest().source( searchSource().query( - functionScoreQuery(termFilter(TEXT_FIELD, "value")) + functionScoreQuery(constantScoreQuery(termQuery(TEXT_FIELD, "value"))) .add(builder) ))).actionGet(); scores[scorecounter] = response.getHits().getAt(0).getScore(); @@ -525,41 +524,6 @@ public class FunctionScoreTests extends ElasticsearchIntegrationTest { } } - @Test - public void testFilterAndQueryGiven() throws IOException, ExecutionException, InterruptedException { - assertAcked(prepareCreate("test").addMapping( - "type", - jsonBuilder().startObject().startObject("type").startObject("properties") - .startObject("filter_field").field("type", "string").endObject() - .startObject("query_field").field("type", "string").endObject() - .startObject("num").field("type", "float").endObject().endObject().endObject().endObject())); - ensureYellow(); - - List indexRequests = new ArrayList<>(); - for (int i = 0; i < 20; i++) { - indexRequests.add( - client().prepareIndex() - .setType("type") - .setId(Integer.toString(i)) - .setIndex("test") - .setSource( - jsonBuilder().startObject().field("query_field", Integer.toString(i % 3)).field("filter_field", Integer.toString(i % 2)).field("num", i).endObject())); - } - - indexRandom(true, true, indexRequests); - - SearchResponse response = client().search( - searchRequest().source( - searchSource().query( - functionScoreQuery(termQuery("query_field", "0"), termFilter("filter_field", "0"), scriptFunction("doc['num'].value")).boostMode("replace")))).get(); - - assertSearchResponse(response); - assertThat(response.getHits().totalHits(), equalTo(4l)); - for (SearchHit hit : response.getHits().getHits()) { - assertThat(Float.parseFloat(hit.getId()), equalTo(hit.getScore())); - } - } - @Test public void testWithEmptyFunctions() throws IOException, ExecutionException, InterruptedException { assertAcked(prepareCreate("test")); diff --git a/src/test/java/org/elasticsearch/search/geo/GeoBoundingBoxTests.java b/src/test/java/org/elasticsearch/search/geo/GeoBoundingBoxTests.java index 0773964acc1..b83cc33693c 100644 --- a/src/test/java/org/elasticsearch/search/geo/GeoBoundingBoxTests.java +++ b/src/test/java/org/elasticsearch/search/geo/GeoBoundingBoxTests.java @@ -27,7 +27,7 @@ import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.geoBoundingBoxFilter; +import static org.elasticsearch.index.query.QueryBuilders.geoBoundingBoxQuery; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.hamcrest.Matchers.anyOf; @@ -90,7 +90,7 @@ public class GeoBoundingBoxTests extends ElasticsearchIntegrationTest { client().admin().indices().prepareRefresh().execute().actionGet(); SearchResponse searchResponse = client().prepareSearch() // from NY - .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxFilter("location").topLeft(40.73, -74.1).bottomRight(40.717, -73.99))) + .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxQuery("location").topLeft(40.73, -74.1).bottomRight(40.717, -73.99))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(2l)); assertThat(searchResponse.getHits().hits().length, equalTo(2)); @@ -99,7 +99,7 @@ public class GeoBoundingBoxTests extends ElasticsearchIntegrationTest { } searchResponse = client().prepareSearch() // from NY - .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxFilter("location").topLeft(40.73, -74.1).bottomRight(40.717, -73.99).type("indexed"))) + .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxQuery("location").topLeft(40.73, -74.1).bottomRight(40.717, -73.99).type("indexed"))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(2l)); assertThat(searchResponse.getHits().hits().length, equalTo(2)); @@ -159,52 +159,52 @@ public class GeoBoundingBoxTests extends ElasticsearchIntegrationTest { refresh(); SearchResponse searchResponse = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxFilter("location").topLeft(41, -11).bottomRight(40, 9))) + .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxQuery("location").topLeft(41, -11).bottomRight(40, 9))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).id(), equalTo("2")); searchResponse = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxFilter("location").topLeft(41, -11).bottomRight(40, 9).type("indexed"))) + .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxQuery("location").topLeft(41, -11).bottomRight(40, 9).type("indexed"))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).id(), equalTo("2")); searchResponse = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxFilter("location").topLeft(41, -9).bottomRight(40, 11))) + .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxQuery("location").topLeft(41, -9).bottomRight(40, 11))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).id(), equalTo("3")); searchResponse = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxFilter("location").topLeft(41, -9).bottomRight(40, 11).type("indexed"))) + .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxQuery("location").topLeft(41, -9).bottomRight(40, 11).type("indexed"))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).id(), equalTo("3")); searchResponse = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxFilter("location").topLeft(11, 171).bottomRight(1, -169))) + .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxQuery("location").topLeft(11, 171).bottomRight(1, -169))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).id(), equalTo("5")); searchResponse = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxFilter("location").topLeft(11, 171).bottomRight(1, -169).type("indexed"))) + .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxQuery("location").topLeft(11, 171).bottomRight(1, -169).type("indexed"))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).id(), equalTo("5")); searchResponse = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxFilter("location").topLeft(9, 169).bottomRight(-1, -171))) + .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxQuery("location").topLeft(9, 169).bottomRight(-1, -171))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).id(), equalTo("9")); searchResponse = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxFilter("location").topLeft(9, 169).bottomRight(-1, -171).type("indexed"))) + .setQuery(filteredQuery(matchAllQuery(), geoBoundingBoxQuery("location").topLeft(9, 169).bottomRight(-1, -171).type("indexed"))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); @@ -238,26 +238,26 @@ public class GeoBoundingBoxTests extends ElasticsearchIntegrationTest { SearchResponse searchResponse = client().prepareSearch() .setQuery( filteredQuery(termQuery("userid", 880), - geoBoundingBoxFilter("location").topLeft(74.579421999999994, 143.5).bottomRight(-66.668903999999998, 113.96875)) + geoBoundingBoxQuery("location").topLeft(74.579421999999994, 143.5).bottomRight(-66.668903999999998, 113.96875)) ).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); searchResponse = client().prepareSearch() .setQuery( filteredQuery(termQuery("userid", 880), - geoBoundingBoxFilter("location").topLeft(74.579421999999994, 143.5).bottomRight(-66.668903999999998, 113.96875).type("indexed")) + geoBoundingBoxQuery("location").topLeft(74.579421999999994, 143.5).bottomRight(-66.668903999999998, 113.96875).type("indexed")) ).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); searchResponse = client().prepareSearch() .setQuery( filteredQuery(termQuery("userid", 534), - geoBoundingBoxFilter("location").topLeft(74.579421999999994, 143.5).bottomRight(-66.668903999999998, 113.96875)) + geoBoundingBoxQuery("location").topLeft(74.579421999999994, 143.5).bottomRight(-66.668903999999998, 113.96875)) ).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); searchResponse = client().prepareSearch() .setQuery( filteredQuery(termQuery("userid", 534), - geoBoundingBoxFilter("location").topLeft(74.579421999999994, 143.5).bottomRight(-66.668903999999998, 113.96875).type("indexed")) + geoBoundingBoxQuery("location").topLeft(74.579421999999994, 143.5).bottomRight(-66.668903999999998, 113.96875).type("indexed")) ).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); } @@ -289,50 +289,50 @@ public class GeoBoundingBoxTests extends ElasticsearchIntegrationTest { SearchResponse searchResponse = client().prepareSearch() .setQuery( filteredQuery(matchAllQuery(), - geoBoundingBoxFilter("location").topLeft(50, -180).bottomRight(-50, 180)) + geoBoundingBoxQuery("location").topLeft(50, -180).bottomRight(-50, 180)) ).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); searchResponse = client().prepareSearch() .setQuery( filteredQuery(matchAllQuery(), - geoBoundingBoxFilter("location").topLeft(50, -180).bottomRight(-50, 180).type("indexed")) + geoBoundingBoxQuery("location").topLeft(50, -180).bottomRight(-50, 180).type("indexed")) ).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); searchResponse = client().prepareSearch() .setQuery( filteredQuery(matchAllQuery(), - geoBoundingBoxFilter("location").topLeft(90, -180).bottomRight(-90, 180)) + geoBoundingBoxQuery("location").topLeft(90, -180).bottomRight(-90, 180)) ).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(2l)); searchResponse = client().prepareSearch() .setQuery( filteredQuery(matchAllQuery(), - geoBoundingBoxFilter("location").topLeft(90, -180).bottomRight(-90, 180).type("indexed")) + geoBoundingBoxQuery("location").topLeft(90, -180).bottomRight(-90, 180).type("indexed")) ).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(2l)); searchResponse = client().prepareSearch() .setQuery( filteredQuery(matchAllQuery(), - geoBoundingBoxFilter("location").topLeft(50, 0).bottomRight(-50, 360)) + geoBoundingBoxQuery("location").topLeft(50, 0).bottomRight(-50, 360)) ).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); searchResponse = client().prepareSearch() .setQuery( filteredQuery(matchAllQuery(), - geoBoundingBoxFilter("location").topLeft(50, 0).bottomRight(-50, 360).type("indexed")) + geoBoundingBoxQuery("location").topLeft(50, 0).bottomRight(-50, 360).type("indexed")) ).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); searchResponse = client().prepareSearch() .setQuery( filteredQuery(matchAllQuery(), - geoBoundingBoxFilter("location").topLeft(90, 0).bottomRight(-90, 360)) + geoBoundingBoxQuery("location").topLeft(90, 0).bottomRight(-90, 360)) ).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(2l)); searchResponse = client().prepareSearch() .setQuery( filteredQuery(matchAllQuery(), - geoBoundingBoxFilter("location").topLeft(90, 0).bottomRight(-90, 360).type("indexed")) + geoBoundingBoxQuery("location").topLeft(90, 0).bottomRight(-90, 360).type("indexed")) ).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(2l)); } diff --git a/src/test/java/org/elasticsearch/search/geo/GeoDistanceTests.java b/src/test/java/org/elasticsearch/search/geo/GeoDistanceTests.java index 2cd797d93db..0d602dfe92f 100644 --- a/src/test/java/org/elasticsearch/search/geo/GeoDistanceTests.java +++ b/src/test/java/org/elasticsearch/search/geo/GeoDistanceTests.java @@ -21,14 +21,12 @@ package org.elasticsearch.search.geo; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.geo.GeoDistance; import org.elasticsearch.common.geo.GeoHashUtils; import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.json.JsonXContent; -import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; @@ -43,11 +41,23 @@ import java.util.Arrays; import java.util.List; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.*; import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; +import static org.elasticsearch.index.query.QueryBuilders.geoDistanceQuery; +import static org.elasticsearch.index.query.QueryBuilders.geoDistanceRangeQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; -import static org.hamcrest.Matchers.*; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFailures; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFirstHit; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertOrderedSearchHits; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.hasId; +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.closeTo; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; /** */ @@ -98,7 +108,7 @@ public class GeoDistanceTests extends ElasticsearchIntegrationTest { .endObject())); SearchResponse searchResponse = client().prepareSearch() // from NY - .setQuery(filteredQuery(matchAllQuery(), geoDistanceFilter("location").distance("3km").point(40.7143528, -74.0059731))) + .setQuery(filteredQuery(matchAllQuery(), geoDistanceQuery("location").distance("3km").point(40.7143528, -74.0059731))) .execute().actionGet(); assertHitCount(searchResponse, 5); assertThat(searchResponse.getHits().hits().length, equalTo(5)); @@ -106,7 +116,7 @@ public class GeoDistanceTests extends ElasticsearchIntegrationTest { assertThat(hit.id(), anyOf(equalTo("1"), equalTo("3"), equalTo("4"), equalTo("5"), equalTo("6"))); } searchResponse = client().prepareSearch() // from NY - .setQuery(filteredQuery(matchAllQuery(), geoDistanceFilter("location").distance("3km").point(40.7143528, -74.0059731).optimizeBbox("indexed"))) + .setQuery(filteredQuery(matchAllQuery(), geoDistanceQuery("location").distance("3km").point(40.7143528, -74.0059731).optimizeBbox("indexed"))) .execute().actionGet(); assertHitCount(searchResponse, 5); assertThat(searchResponse.getHits().hits().length, equalTo(5)); @@ -116,7 +126,7 @@ public class GeoDistanceTests extends ElasticsearchIntegrationTest { // now with a PLANE type searchResponse = client().prepareSearch() // from NY - .setQuery(filteredQuery(matchAllQuery(), geoDistanceFilter("location").distance("3km").geoDistance(GeoDistance.PLANE).point(40.7143528, -74.0059731))) + .setQuery(filteredQuery(matchAllQuery(), geoDistanceQuery("location").distance("3km").geoDistance(GeoDistance.PLANE).point(40.7143528, -74.0059731))) .execute().actionGet(); assertHitCount(searchResponse, 5); assertThat(searchResponse.getHits().hits().length, equalTo(5)); @@ -127,7 +137,7 @@ public class GeoDistanceTests extends ElasticsearchIntegrationTest { // factor type is really too small for this resolution searchResponse = client().prepareSearch() // from NY - .setQuery(filteredQuery(matchAllQuery(), geoDistanceFilter("location").distance("2km").point(40.7143528, -74.0059731))) + .setQuery(filteredQuery(matchAllQuery(), geoDistanceQuery("location").distance("2km").point(40.7143528, -74.0059731))) .execute().actionGet(); assertHitCount(searchResponse, 4); assertThat(searchResponse.getHits().hits().length, equalTo(4)); @@ -135,7 +145,7 @@ public class GeoDistanceTests extends ElasticsearchIntegrationTest { assertThat(hit.id(), anyOf(equalTo("1"), equalTo("3"), equalTo("4"), equalTo("5"))); } searchResponse = client().prepareSearch() // from NY - .setQuery(filteredQuery(matchAllQuery(), geoDistanceFilter("location").distance("2km").point(40.7143528, -74.0059731).optimizeBbox("indexed"))) + .setQuery(filteredQuery(matchAllQuery(), geoDistanceQuery("location").distance("2km").point(40.7143528, -74.0059731).optimizeBbox("indexed"))) .execute().actionGet(); assertHitCount(searchResponse, 4); assertThat(searchResponse.getHits().hits().length, equalTo(4)); @@ -144,7 +154,7 @@ public class GeoDistanceTests extends ElasticsearchIntegrationTest { } searchResponse = client().prepareSearch() // from NY - .setQuery(filteredQuery(matchAllQuery(), geoDistanceFilter("location").distance("1.242mi").point(40.7143528, -74.0059731))) + .setQuery(filteredQuery(matchAllQuery(), geoDistanceQuery("location").distance("1.242mi").point(40.7143528, -74.0059731))) .execute().actionGet(); assertHitCount(searchResponse, 4); assertThat(searchResponse.getHits().hits().length, equalTo(4)); @@ -152,7 +162,7 @@ public class GeoDistanceTests extends ElasticsearchIntegrationTest { assertThat(hit.id(), anyOf(equalTo("1"), equalTo("3"), equalTo("4"), equalTo("5"))); } searchResponse = client().prepareSearch() // from NY - .setQuery(filteredQuery(matchAllQuery(), geoDistanceFilter("location").distance("1.242mi").point(40.7143528, -74.0059731).optimizeBbox("indexed"))) + .setQuery(filteredQuery(matchAllQuery(), geoDistanceQuery("location").distance("1.242mi").point(40.7143528, -74.0059731).optimizeBbox("indexed"))) .execute().actionGet(); assertHitCount(searchResponse, 4); assertThat(searchResponse.getHits().hits().length, equalTo(4)); @@ -161,7 +171,7 @@ public class GeoDistanceTests extends ElasticsearchIntegrationTest { } searchResponse = client().prepareSearch() // from NY - .setQuery(filteredQuery(matchAllQuery(), geoDistanceRangeFilter("location").from("1.0km").to("2.0km").point(40.7143528, -74.0059731))) + .setQuery(filteredQuery(matchAllQuery(), geoDistanceRangeQuery("location").from("1.0km").to("2.0km").point(40.7143528, -74.0059731))) .execute().actionGet(); assertHitCount(searchResponse, 2); assertThat(searchResponse.getHits().hits().length, equalTo(2)); @@ -169,7 +179,7 @@ public class GeoDistanceTests extends ElasticsearchIntegrationTest { assertThat(hit.id(), anyOf(equalTo("4"), equalTo("5"))); } searchResponse = client().prepareSearch() // from NY - .setQuery(filteredQuery(matchAllQuery(), geoDistanceRangeFilter("location").from("1.0km").to("2.0km").point(40.7143528, -74.0059731).optimizeBbox("indexed"))) + .setQuery(filteredQuery(matchAllQuery(), geoDistanceRangeQuery("location").from("1.0km").to("2.0km").point(40.7143528, -74.0059731).optimizeBbox("indexed"))) .execute().actionGet(); assertHitCount(searchResponse, 2); assertThat(searchResponse.getHits().hits().length, equalTo(2)); @@ -178,13 +188,13 @@ public class GeoDistanceTests extends ElasticsearchIntegrationTest { } searchResponse = client().prepareSearch() // from NY - .setQuery(filteredQuery(matchAllQuery(), geoDistanceRangeFilter("location").to("2.0km").point(40.7143528, -74.0059731))) + .setQuery(filteredQuery(matchAllQuery(), geoDistanceRangeQuery("location").to("2.0km").point(40.7143528, -74.0059731))) .execute().actionGet(); assertHitCount(searchResponse, 4); assertThat(searchResponse.getHits().hits().length, equalTo(4)); searchResponse = client().prepareSearch() // from NY - .setQuery(filteredQuery(matchAllQuery(), geoDistanceRangeFilter("location").from("2.0km").point(40.7143528, -74.0059731))) + .setQuery(filteredQuery(matchAllQuery(), geoDistanceRangeQuery("location").from("2.0km").point(40.7143528, -74.0059731))) .execute().actionGet(); assertHitCount(searchResponse, 3); assertThat(searchResponse.getHits().hits().length, equalTo(3)); @@ -574,7 +584,7 @@ public class GeoDistanceTests extends ElasticsearchIntegrationTest { searchResponse = client().prepareSearch("companies").setQuery(matchAllQuery()) .addSort( - SortBuilders.geoDistanceSort("branches.location").setNestedFilter(termFilter("branches.name", "brooklyn")) + SortBuilders.geoDistanceSort("branches.location").setNestedFilter(termQuery("branches.name", "brooklyn")) .point(40.7143528, -74.0059731).sortMode("avg").order(SortOrder.ASC) ) .execute().actionGet(); @@ -629,7 +639,7 @@ public class GeoDistanceTests extends ElasticsearchIntegrationTest { SearchResponse result = client().prepareSearch("locations") .setQuery(QueryBuilders.matchAllQuery()) - .setPostFilter(FilterBuilders.geoDistanceFilter("pin") + .setPostFilter(QueryBuilders.geoDistanceQuery("pin") .geoDistance(GeoDistance.ARC) .lat(lat).lon(lon) .distance("1m")) @@ -665,7 +675,7 @@ public class GeoDistanceTests extends ElasticsearchIntegrationTest { long matches = -1; for (String optimizeBbox : Arrays.asList("none", "memory", "indexed")) { SearchResponse resp = client().prepareSearch("index").setSize(0).setQuery(QueryBuilders.constantScoreQuery( - FilterBuilders.geoDistanceFilter("location").point(originLat, originLon).distance(distance).geoDistance(geoDistance).optimizeBbox(optimizeBbox))).execute().actionGet(); + QueryBuilders.geoDistanceQuery("location").point(originLat, originLon).distance(distance).geoDistance(geoDistance).optimizeBbox(optimizeBbox))).execute().actionGet(); assertSearchResponse(resp); logger.info("{} -> {} hits", optimizeBbox, resp.getHits().totalHits()); if (matches < 0) { diff --git a/src/test/java/org/elasticsearch/search/geo/GeoFilterTests.java b/src/test/java/org/elasticsearch/search/geo/GeoFilterTests.java index 4b7eeadf59e..5895b94fc01 100644 --- a/src/test/java/org/elasticsearch/search/geo/GeoFilterTests.java +++ b/src/test/java/org/elasticsearch/search/geo/GeoFilterTests.java @@ -43,8 +43,8 @@ import org.elasticsearch.common.geo.builders.PolygonBuilder; import org.elasticsearch.common.geo.builders.ShapeBuilder; import org.elasticsearch.common.io.Streams; import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.FilterBuilders; -import org.elasticsearch.index.query.GeohashCellFilter; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.index.query.GeohashCellQuery; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.test.ElasticsearchIntegrationTest; @@ -59,7 +59,7 @@ import java.util.*; import java.util.zip.GZIPInputStream; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; import static org.hamcrest.Matchers.*; @@ -254,7 +254,7 @@ public class GeoFilterTests extends ElasticsearchIntegrationTest { // Point in polygon SearchResponse result = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(FilterBuilders.geoIntersectionFilter("area", ShapeBuilder.newPoint(3, 3))) + .setPostFilter(QueryBuilders.geoIntersectionQuery("area", ShapeBuilder.newPoint(3, 3))) .execute().actionGet(); assertHitCount(result, 1); assertFirstHit(result, hasId("1")); @@ -262,7 +262,7 @@ public class GeoFilterTests extends ElasticsearchIntegrationTest { // Point in polygon hole result = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(FilterBuilders.geoIntersectionFilter("area", ShapeBuilder.newPoint(4.5, 4.5))) + .setPostFilter(QueryBuilders.geoIntersectionQuery("area", ShapeBuilder.newPoint(4.5, 4.5))) .execute().actionGet(); assertHitCount(result, 0); @@ -273,7 +273,7 @@ public class GeoFilterTests extends ElasticsearchIntegrationTest { // Point on polygon border result = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(FilterBuilders.geoIntersectionFilter("area", ShapeBuilder.newPoint(10.0, 5.0))) + .setPostFilter(QueryBuilders.geoIntersectionQuery("area", ShapeBuilder.newPoint(10.0, 5.0))) .execute().actionGet(); assertHitCount(result, 1); assertFirstHit(result, hasId("1")); @@ -281,7 +281,7 @@ public class GeoFilterTests extends ElasticsearchIntegrationTest { // Point on hole border result = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(FilterBuilders.geoIntersectionFilter("area", ShapeBuilder.newPoint(5.0, 2.0))) + .setPostFilter(QueryBuilders.geoIntersectionQuery("area", ShapeBuilder.newPoint(5.0, 2.0))) .execute().actionGet(); assertHitCount(result, 1); assertFirstHit(result, hasId("1")); @@ -290,14 +290,14 @@ public class GeoFilterTests extends ElasticsearchIntegrationTest { // Point not in polygon result = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(FilterBuilders.geoDisjointFilter("area", ShapeBuilder.newPoint(3, 3))) + .setPostFilter(QueryBuilders.geoDisjointQuery("area", ShapeBuilder.newPoint(3, 3))) .execute().actionGet(); assertHitCount(result, 0); // Point in polygon hole result = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(FilterBuilders.geoDisjointFilter("area", ShapeBuilder.newPoint(4.5, 4.5))) + .setPostFilter(QueryBuilders.geoDisjointQuery("area", ShapeBuilder.newPoint(4.5, 4.5))) .execute().actionGet(); assertHitCount(result, 1); assertFirstHit(result, hasId("1")); @@ -318,7 +318,7 @@ public class GeoFilterTests extends ElasticsearchIntegrationTest { // re-check point on polygon hole result = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(FilterBuilders.geoIntersectionFilter("area", ShapeBuilder.newPoint(4.5, 4.5))) + .setPostFilter(QueryBuilders.geoIntersectionQuery("area", ShapeBuilder.newPoint(4.5, 4.5))) .execute().actionGet(); assertHitCount(result, 1); assertFirstHit(result, hasId("2")); @@ -338,7 +338,7 @@ public class GeoFilterTests extends ElasticsearchIntegrationTest { result = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(FilterBuilders.geoWithinFilter("area", builder)) + .setPostFilter(QueryBuilders.geoWithinQuery("area", builder)) .execute().actionGet(); assertHitCount(result, 2); } @@ -364,25 +364,25 @@ public class GeoFilterTests extends ElasticsearchIntegrationTest { result = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(FilterBuilders.geoIntersectionFilter("area", ShapeBuilder.newPoint(174, -4))) + .setPostFilter(QueryBuilders.geoIntersectionQuery("area", ShapeBuilder.newPoint(174, -4))) .execute().actionGet(); assertHitCount(result, 1); result = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(FilterBuilders.geoIntersectionFilter("area", ShapeBuilder.newPoint(-174, -4))) + .setPostFilter(QueryBuilders.geoIntersectionQuery("area", ShapeBuilder.newPoint(-174, -4))) .execute().actionGet(); assertHitCount(result, 1); result = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(FilterBuilders.geoIntersectionFilter("area", ShapeBuilder.newPoint(180, -4))) + .setPostFilter(QueryBuilders.geoIntersectionQuery("area", ShapeBuilder.newPoint(180, -4))) .execute().actionGet(); assertHitCount(result, 0); result = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(FilterBuilders.geoIntersectionFilter("area", ShapeBuilder.newPoint(180, -6))) + .setPostFilter(QueryBuilders.geoIntersectionQuery("area", ShapeBuilder.newPoint(180, -6))) .execute().actionGet(); assertHitCount(result, 1); } @@ -432,7 +432,7 @@ public class GeoFilterTests extends ElasticsearchIntegrationTest { SearchResponse world = client().prepareSearch().addField("pin").setQuery( filteredQuery( matchAllQuery(), - geoBoundingBoxFilter("pin") + geoBoundingBoxQuery("pin") .topLeft(90, -179.99999) .bottomRight(-90, 179.99999)) ).execute().actionGet(); @@ -442,7 +442,7 @@ public class GeoFilterTests extends ElasticsearchIntegrationTest { SearchResponse distance = client().prepareSearch().addField("pin").setQuery( filteredQuery( matchAllQuery(), - geoDistanceFilter("pin").distance("425km").point(51.11, 9.851) + geoDistanceQuery("pin").distance("425km").point(51.11, 9.851) )).execute().actionGet(); assertHitCount(distance, 5); @@ -495,25 +495,25 @@ public class GeoFilterTests extends ElasticsearchIntegrationTest { client().admin().indices().prepareRefresh("locations").execute().actionGet(); - Map expectedCounts = new HashMap<>(); - Map expectedResults = new HashMap<>(); + Map expectedCounts = new HashMap<>(); + Map expectedResults = new HashMap<>(); - expectedCounts.put(geoHashCellFilter("pin", geohash, false), 1L); + expectedCounts.put(geoHashCellQuery("pin", geohash, false), 1L); - expectedCounts.put(geoHashCellFilter("pin", geohash.substring(0, geohash.length() - 1), true), 2L + neighbors.size() + parentNeighbors.size()); + expectedCounts.put(geoHashCellQuery("pin", geohash.substring(0, geohash.length() - 1), true), 2L + neighbors.size() + parentNeighbors.size()); // Testing point formats and precision GeoPoint point = GeoHashUtils.decode(geohash); int precision = geohash.length(); - expectedCounts.put(geoHashCellFilter("pin", point).neighbors(true).precision(precision), 1L + neighbors.size()); + expectedCounts.put(geoHashCellQuery("pin", point).neighbors(true).precision(precision), 1L + neighbors.size()); logger.info("random testing of setting"); - List filterBuilders = new ArrayList<>(expectedCounts.keySet()); + List filterBuilders = new ArrayList<>(expectedCounts.keySet()); for (int j = filterBuilders.size() * 2 * randomIntBetween(1, 5); j > 0; j--) { Collections.shuffle(filterBuilders, getRandom()); - for (GeohashCellFilter.Builder builder : filterBuilders) { + for (GeohashCellQuery.Builder builder : filterBuilders) { try { long expectedCount = expectedCounts.get(builder); SearchResponse response = client().prepareSearch("locations").setQuery(QueryBuilders.matchAllQuery()) diff --git a/src/test/java/org/elasticsearch/search/geo/GeoPolygonTests.java b/src/test/java/org/elasticsearch/search/geo/GeoPolygonTests.java index d370041a24a..8b7b505059f 100644 --- a/src/test/java/org/elasticsearch/search/geo/GeoPolygonTests.java +++ b/src/test/java/org/elasticsearch/search/geo/GeoPolygonTests.java @@ -27,7 +27,7 @@ import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.geoPolygonFilter; +import static org.elasticsearch.index.query.QueryBuilders.geoPolygonQuery; import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; @@ -88,7 +88,7 @@ public class GeoPolygonTests extends ElasticsearchIntegrationTest { public void simplePolygonTest() throws Exception { SearchResponse searchResponse = client().prepareSearch("test") // from NY - .setQuery(filteredQuery(matchAllQuery(), geoPolygonFilter("location") + .setQuery(filteredQuery(matchAllQuery(), geoPolygonQuery("location") .addPoint(40.7, -74.0) .addPoint(40.7, -74.1) .addPoint(40.8, -74.1) diff --git a/src/test/java/org/elasticsearch/search/geo/GeoShapeIntegrationTests.java b/src/test/java/org/elasticsearch/search/geo/GeoShapeIntegrationTests.java index 4cec4c431f6..13e4d0d6554 100644 --- a/src/test/java/org/elasticsearch/search/geo/GeoShapeIntegrationTests.java +++ b/src/test/java/org/elasticsearch/search/geo/GeoShapeIntegrationTests.java @@ -24,33 +24,36 @@ import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.routing.IndexShardRoutingTable; -import org.elasticsearch.index.IndexService; -import org.elasticsearch.index.mapper.FieldMapper; -import org.elasticsearch.index.mapper.geo.GeoShapeFieldMapper; -import org.elasticsearch.indices.IndicesService; -import org.elasticsearch.test.geo.RandomShapeGenerator; import org.elasticsearch.common.geo.ShapeRelation; import org.elasticsearch.common.geo.builders.GeometryCollectionBuilder; import org.elasticsearch.common.geo.builders.ShapeBuilder; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.FilterBuilders; -import org.elasticsearch.index.query.GeoShapeFilterBuilder; +import org.elasticsearch.index.IndexService; +import org.elasticsearch.index.mapper.FieldMapper; +import org.elasticsearch.index.mapper.geo.GeoShapeFieldMapper; import org.elasticsearch.index.query.GeoShapeQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.indices.IndicesService; import org.elasticsearch.test.ElasticsearchIntegrationTest; +import org.elasticsearch.test.geo.RandomShapeGenerator; import org.junit.Test; import java.io.IOException; -import java.util.List; import java.util.Locale; -import java.util.Map; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.geoIntersectionFilter; -import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; -import static org.hamcrest.Matchers.*; +import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; +import static org.elasticsearch.index.query.QueryBuilders.geoIntersectionQuery; +import static org.elasticsearch.index.query.QueryBuilders.geoIntersectionQuery; +import static org.elasticsearch.index.query.QueryBuilders.geoShapeQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.nullValue; public class GeoShapeIntegrationTests extends ElasticsearchIntegrationTest { @@ -102,7 +105,7 @@ public class GeoShapeIntegrationTests extends ElasticsearchIntegrationTest { SearchResponse searchResponse = client().prepareSearch() .setQuery(filteredQuery(matchAllQuery(), - geoIntersectionFilter("location", shape))) + geoIntersectionQuery("location", shape))) .execute().actionGet(); assertSearchResponse(searchResponse); @@ -152,7 +155,7 @@ public class GeoShapeIntegrationTests extends ElasticsearchIntegrationTest { // used the bottom-level optimization in SpatialPrefixTree#recursiveGetNodes. SearchResponse searchResponse = client().prepareSearch() .setQuery(filteredQuery(matchAllQuery(), - geoIntersectionFilter("location", query))) + geoIntersectionQuery("location", query))) .execute().actionGet(); assertSearchResponse(searchResponse); @@ -188,7 +191,7 @@ public class GeoShapeIntegrationTests extends ElasticsearchIntegrationTest { SearchResponse searchResponse = client().prepareSearch("test") .setQuery(filteredQuery(matchAllQuery(), - geoIntersectionFilter("location", "Big_Rectangle", "shape_type"))) + geoIntersectionQuery("location", "Big_Rectangle", "shape_type"))) .execute().actionGet(); assertSearchResponse(searchResponse); @@ -290,28 +293,28 @@ public class GeoShapeIntegrationTests extends ElasticsearchIntegrationTest { .endObject().endObject())); ensureSearchable("test", "shapes"); - GeoShapeFilterBuilder filter = FilterBuilders.geoShapeFilter("location", "1", "type", ShapeRelation.INTERSECTS) + GeoShapeQueryBuilder filter = QueryBuilders.geoShapeQuery("location", "1", "type", ShapeRelation.INTERSECTS) .indexedShapeIndex("shapes") .indexedShapePath("location"); SearchResponse result = client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()) .setPostFilter(filter).get(); assertSearchResponse(result); assertHitCount(result, 1); - filter = FilterBuilders.geoShapeFilter("location", "1", "type", ShapeRelation.INTERSECTS) + filter = QueryBuilders.geoShapeQuery("location", "1", "type", ShapeRelation.INTERSECTS) .indexedShapeIndex("shapes") .indexedShapePath("1.location"); result = client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()) .setPostFilter(filter).get(); assertSearchResponse(result); assertHitCount(result, 1); - filter = FilterBuilders.geoShapeFilter("location", "1", "type", ShapeRelation.INTERSECTS) + filter = QueryBuilders.geoShapeQuery("location", "1", "type", ShapeRelation.INTERSECTS) .indexedShapeIndex("shapes") .indexedShapePath("1.2.location"); result = client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()) .setPostFilter(filter).get(); assertSearchResponse(result); assertHitCount(result, 1); - filter = FilterBuilders.geoShapeFilter("location", "1", "type", ShapeRelation.INTERSECTS) + filter = QueryBuilders.geoShapeQuery("location", "1", "type", ShapeRelation.INTERSECTS) .indexedShapeIndex("shapes") .indexedShapePath("1.2.3.location"); result = client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()) @@ -364,7 +367,7 @@ public class GeoShapeIntegrationTests extends ElasticsearchIntegrationTest { ShapeBuilder filterShape = (gcb.getShapeAt(randomIntBetween(0, gcb.numShapes() - 1))); - GeoShapeFilterBuilder filter = FilterBuilders.geoShapeFilter("location", filterShape, ShapeRelation.INTERSECTS); + GeoShapeQueryBuilder filter = QueryBuilders.geoShapeQuery("location", filterShape, ShapeRelation.INTERSECTS); SearchResponse result = client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()) .setPostFilter(filter).get(); assertSearchResponse(result); @@ -403,17 +406,17 @@ public class GeoShapeIntegrationTests extends ElasticsearchIntegrationTest { .setSource(docSource)); ensureSearchable("test"); - GeoShapeFilterBuilder filter = FilterBuilders.geoShapeFilter("location", ShapeBuilder.newGeometryCollection().polygon(ShapeBuilder.newPolygon().point(99.0, -1.0).point(99.0, 3.0).point(103.0, 3.0).point(103.0, -1.0).point(99.0, -1.0)), ShapeRelation.INTERSECTS); + GeoShapeQueryBuilder filter = QueryBuilders.geoShapeQuery("location", ShapeBuilder.newGeometryCollection().polygon(ShapeBuilder.newPolygon().point(99.0, -1.0).point(99.0, 3.0).point(103.0, 3.0).point(103.0, -1.0).point(99.0, -1.0)), ShapeRelation.INTERSECTS); SearchResponse result = client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()) .setPostFilter(filter).get(); assertSearchResponse(result); assertHitCount(result, 1); - filter = FilterBuilders.geoShapeFilter("location", ShapeBuilder.newGeometryCollection().polygon(ShapeBuilder.newPolygon().point(199.0, -11.0).point(199.0, 13.0).point(193.0, 13.0).point(193.0, -11.0).point(199.0, -11.0)), ShapeRelation.INTERSECTS); + filter = QueryBuilders.geoShapeQuery("location", ShapeBuilder.newGeometryCollection().polygon(ShapeBuilder.newPolygon().point(199.0, -11.0).point(199.0, 13.0).point(193.0, 13.0).point(193.0, -11.0).point(199.0, -11.0)), ShapeRelation.INTERSECTS); result = client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()) .setPostFilter(filter).get(); assertSearchResponse(result); assertHitCount(result, 0); - filter = FilterBuilders.geoShapeFilter("location", ShapeBuilder.newGeometryCollection() + filter = QueryBuilders.geoShapeQuery("location", ShapeBuilder.newGeometryCollection() .polygon(ShapeBuilder.newPolygon().point(99.0, -1.0).point(99.0, 3.0).point(103.0, 3.0).point(103.0, -1.0).point(99.0, -1.0)) .polygon(ShapeBuilder.newPolygon().point(199.0, -11.0).point(199.0, 13.0).point(193.0, 13.0).point(193.0, -11.0).point(199.0, -11.0)), ShapeRelation.INTERSECTS); result = client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()) diff --git a/src/test/java/org/elasticsearch/search/highlight/HighlighterSearchTests.java b/src/test/java/org/elasticsearch/search/highlight/HighlighterSearchTests.java index 9729d8e0439..7758c3fca13 100644 --- a/src/test/java/org/elasticsearch/search/highlight/HighlighterSearchTests.java +++ b/src/test/java/org/elasticsearch/search/highlight/HighlighterSearchTests.java @@ -32,7 +32,7 @@ import org.elasticsearch.common.settings.ImmutableSettings.Builder; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.BoostableQueryBuilder; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.IdsQueryBuilder; import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.index.query.MatchQueryBuilder.Operator; @@ -56,8 +56,8 @@ import java.util.Map; import static org.elasticsearch.client.Requests.searchRequest; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.missingFilter; -import static org.elasticsearch.index.query.FilterBuilders.typeFilter; +import static org.elasticsearch.index.query.QueryBuilders.missingQuery; +import static org.elasticsearch.index.query.QueryBuilders.typeQuery; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.boostingQuery; import static org.elasticsearch.index.query.QueryBuilders.commonTermsQuery; @@ -1400,7 +1400,7 @@ public class HighlighterSearchTests extends ElasticsearchIntegrationTest { .setSource("field4", "a quick fast blue car").get(); refresh(); - source = searchSource().postFilter(typeFilter("type2")).query(matchPhrasePrefixQuery("field3", "fast bro")) + source = searchSource().postFilter(typeQuery("type2")).query(matchPhrasePrefixQuery("field3", "fast bro")) .highlight(highlight().field("field3").order("score").preTags("").postTags("")); searchResponse = client().search(searchRequest("test").source(source)).actionGet(); @@ -1408,7 +1408,7 @@ public class HighlighterSearchTests extends ElasticsearchIntegrationTest { assertHighlight(searchResponse, 0, "field3", 0, 1, equalTo("The quick brown fox jumps over the lazy dog")); logger.info("--> highlighting and searching on field4"); - source = searchSource().postFilter(typeFilter("type2")).query(matchPhrasePrefixQuery("field4", "the fast bro")) + source = searchSource().postFilter(typeQuery("type2")).query(matchPhrasePrefixQuery("field4", "the fast bro")) .highlight(highlight().field("field4").order("score").preTags("").postTags("")); searchResponse = client().search(searchRequest("test").source(source)).actionGet(); @@ -1416,7 +1416,7 @@ public class HighlighterSearchTests extends ElasticsearchIntegrationTest { assertHighlight(searchResponse, 1, "field4", 0, 1, anyOf(equalTo("The quick browse button is a fancy thing, right bro?"), equalTo("The quick brown fox jumps over the lazy dog"))); logger.info("--> highlighting and searching on field4"); - source = searchSource().postFilter(typeFilter("type2")).query(matchPhrasePrefixQuery("field4", "a fast quick blue ca")) + source = searchSource().postFilter(typeQuery("type2")).query(matchPhrasePrefixQuery("field4", "a fast quick blue ca")) .highlight(highlight().field("field4").order("score").preTags("").postTags("")); searchResponse = client().search(searchRequest("test").source(source)).actionGet(); @@ -2454,7 +2454,7 @@ public class HighlighterSearchTests extends ElasticsearchIntegrationTest { logger.info("--> highlighting and searching on field1"); SearchSourceBuilder source = searchSource().query(boolQuery() - .should(constantScoreQuery(FilterBuilders.missingFilter("field1"))) + .should(constantScoreQuery(QueryBuilders.missingQuery("field1"))) .should(matchQuery("field1", "test")) .should(filteredQuery(queryStringQuery("field1:photo*").rewrite(randomFrom(REWRITE_METHODS)), null))) .highlight(highlight().field("field1")); @@ -2488,7 +2488,7 @@ public class HighlighterSearchTests extends ElasticsearchIntegrationTest { refresh(); logger.info("--> highlighting and searching on field1"); - SearchSourceBuilder source = searchSource().query(filteredQuery(queryStringQuery("field1:photo*").rewrite(randomFrom(REWRITE_METHODS)), missingFilter("field_null"))) + SearchSourceBuilder source = searchSource().query(filteredQuery(queryStringQuery("field1:photo*").rewrite(randomFrom(REWRITE_METHODS)), missingQuery("field_null"))) .highlight(highlight().field("field1")); SearchResponse searchResponse = client().prepareSearch("test").setSource(source.buildAsBytes()).get(); assertHighlight(searchResponse, 0, "field1", 0, 1, equalTo("The photography word will get highlighted")); diff --git a/src/test/java/org/elasticsearch/search/innerhits/InnerHitsTests.java b/src/test/java/org/elasticsearch/search/innerhits/InnerHitsTests.java index 2de5348149d..6c517fa199b 100644 --- a/src/test/java/org/elasticsearch/search/innerhits/InnerHitsTests.java +++ b/src/test/java/org/elasticsearch/search/innerhits/InnerHitsTests.java @@ -39,9 +39,8 @@ import java.util.List; import java.util.Locale; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.hasChildFilter; -import static org.elasticsearch.index.query.FilterBuilders.nestedFilter; -import static org.elasticsearch.index.query.FilterBuilders.queryFilter; +import static org.elasticsearch.index.query.QueryBuilders.hasChildQuery; +import static org.elasticsearch.index.query.QueryBuilders.nestedQuery; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; import static org.hamcrest.Matchers.*; @@ -115,7 +114,7 @@ public class InnerHitsTests extends ElasticsearchIntegrationTest { client().prepareSearch("articles") .setQuery(nestedQuery("comments", matchQuery("comments.message", "elephant")).innerHit(new QueryInnerHitBuilder().setName("comment"))).request(), client().prepareSearch("articles") - .setQuery(nestedQuery("comments", queryFilter(matchQuery("comments.message", "elephant"))).innerHit(new QueryInnerHitBuilder().setName("comment").addSort("_doc", SortOrder.DESC))).request() + .setQuery(nestedQuery("comments", matchQuery("comments.message", "elephant")).innerHit(new QueryInnerHitBuilder().setName("comment").addSort("_doc", SortOrder.DESC))).request() }; for (SearchRequest searchRequest : searchRequests) { SearchResponse response = client().search(searchRequest).actionGet(); @@ -208,8 +207,8 @@ public class InnerHitsTests extends ElasticsearchIntegrationTest { boolQuery.should(nestedQuery("field1", matchAllQuery()).innerHit(new QueryInnerHitBuilder().setName("a").addSort("_doc", SortOrder.DESC).setSize(size))); boolQuery.should(nestedQuery("field2", matchAllQuery()).innerHit(new QueryInnerHitBuilder().setName("b").addSort("_doc", SortOrder.DESC).setSize(size))); } else { - boolQuery.should(constantScoreQuery(nestedFilter("field1", matchAllQuery()).innerHit(new QueryInnerHitBuilder().setName("a").addSort("_doc", SortOrder.DESC).setSize(size)))); - boolQuery.should(constantScoreQuery(nestedFilter("field2", matchAllQuery()).innerHit(new QueryInnerHitBuilder().setName("b").addSort("_doc", SortOrder.DESC).setSize(size)))); + boolQuery.should(constantScoreQuery(nestedQuery("field1", matchAllQuery()).innerHit(new QueryInnerHitBuilder().setName("a").addSort("_doc", SortOrder.DESC).setSize(size)))); + boolQuery.should(constantScoreQuery(nestedQuery("field2", matchAllQuery()).innerHit(new QueryInnerHitBuilder().setName("b").addSort("_doc", SortOrder.DESC).setSize(size)))); } searchResponse = client().prepareSearch("idx") .setQuery(boolQuery) @@ -393,8 +392,8 @@ public class InnerHitsTests extends ElasticsearchIntegrationTest { boolQuery.should(hasChildQuery("child1", matchAllQuery()).innerHit(new QueryInnerHitBuilder().setName("a").addSort("_uid", SortOrder.ASC).setSize(size))); boolQuery.should(hasChildQuery("child2", matchAllQuery()).innerHit(new QueryInnerHitBuilder().setName("b").addSort("_uid", SortOrder.ASC).setSize(size))); } else { - boolQuery.should(constantScoreQuery(hasChildFilter("child1", matchAllQuery()).innerHit(new QueryInnerHitBuilder().setName("a").addSort("_uid", SortOrder.ASC).setSize(size)))); - boolQuery.should(constantScoreQuery(hasChildFilter("child2", matchAllQuery()).innerHit(new QueryInnerHitBuilder().setName("b").addSort("_uid", SortOrder.ASC).setSize(size)))); + boolQuery.should(constantScoreQuery(hasChildQuery("child1", matchAllQuery()).innerHit(new QueryInnerHitBuilder().setName("a").addSort("_uid", SortOrder.ASC).setSize(size)))); + boolQuery.should(constantScoreQuery(hasChildQuery("child2", matchAllQuery()).innerHit(new QueryInnerHitBuilder().setName("b").addSort("_uid", SortOrder.ASC).setSize(size)))); } searchResponse = client().prepareSearch("idx") .setSize(numDocs) diff --git a/src/test/java/org/elasticsearch/search/matchedqueries/MatchedQueriesTests.java b/src/test/java/org/elasticsearch/search/matchedqueries/MatchedQueriesTests.java index dc1bef9e8a4..b079b2f6e6b 100644 --- a/src/test/java/org/elasticsearch/search/matchedqueries/MatchedQueriesTests.java +++ b/src/test/java/org/elasticsearch/search/matchedqueries/MatchedQueriesTests.java @@ -25,7 +25,6 @@ import org.elasticsearch.search.SearchHit; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.junit.Test; -import static org.elasticsearch.index.query.FilterBuilders.*; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; import static org.hamcrest.Matchers.equalTo; @@ -47,7 +46,7 @@ public class MatchedQueriesTests extends ElasticsearchIntegrationTest { refresh(); SearchResponse searchResponse = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), orFilter(rangeFilter("number").lte(2).filterName("test1"), rangeFilter("number").gt(2).filterName("test2")))).get(); + .setQuery(filteredQuery(matchAllQuery(), orQuery(rangeQuery("number").lte(2).queryName("test1"), rangeQuery("number").gt(2).queryName("test2")))).get(); assertHitCount(searchResponse, 3l); for (SearchHit hit : searchResponse.getHits()) { if (hit.id().equals("1") || hit.id().equals("2")) { @@ -89,9 +88,9 @@ public class MatchedQueriesTests extends ElasticsearchIntegrationTest { SearchResponse searchResponse = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(orFilter( - termFilter("name", "test").filterName("name"), - termFilter("title", "title1").filterName("title"))).get(); + .setPostFilter(orQuery( + termQuery("name", "test").queryName("name"), + termQuery("title", "title1").queryName("title"))).get(); assertHitCount(searchResponse, 3l); for (SearchHit hit : searchResponse.getHits()) { if (hit.id().equals("1")) { @@ -108,9 +107,9 @@ public class MatchedQueriesTests extends ElasticsearchIntegrationTest { searchResponse = client().prepareSearch() .setQuery(matchAllQuery()) - .setPostFilter(queryFilter(boolQuery() + .setPostFilter(boolQuery() .should(termQuery("name", "test").queryName("name")) - .should(termQuery("title", "title1").queryName("title")))).get(); + .should(termQuery("title", "title1").queryName("title"))).get(); assertHitCount(searchResponse, 3l); for (SearchHit hit : searchResponse.getHits()) { @@ -138,8 +137,8 @@ public class MatchedQueriesTests extends ElasticsearchIntegrationTest { refresh(); SearchResponse searchResponse = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), termsFilter("title", "title1", "title2", "title3").filterName("title"))) - .setPostFilter(termFilter("name", "test").filterName("name")).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("title", "title1", "title2", "title3").queryName("title"))) + .setPostFilter(termQuery("name", "test").queryName("name")).get(); assertHitCount(searchResponse, 3l); for (SearchHit hit : searchResponse.getHits()) { if (hit.id().equals("1") || hit.id().equals("2") || hit.id().equals("3")) { @@ -153,7 +152,7 @@ public class MatchedQueriesTests extends ElasticsearchIntegrationTest { searchResponse = client().prepareSearch() .setQuery(termsQuery("title", "title1", "title2", "title3").queryName("title")) - .setPostFilter(queryFilter(matchQuery("name", "test").queryName("name"))).get(); + .setPostFilter(matchQuery("name", "test").queryName("name")).get(); assertHitCount(searchResponse, 3l); for (SearchHit hit : searchResponse.getHits()) { if (hit.id().equals("1") || hit.id().equals("2") || hit.id().equals("3")) { @@ -178,10 +177,10 @@ public class MatchedQueriesTests extends ElasticsearchIntegrationTest { SearchResponse searchResponse = client().prepareSearch() .setQuery(filteredQuery(matchAllQuery(), - orFilter( - indicesFilter(termFilter("title", "title1").filterName("title1"), "test1") - .noMatchFilter(termFilter("title", "title2").filterName("title2")).filterName("indices_filter"), - termFilter("title", "title3").filterName("title3")).filterName("or"))).get(); + orQuery( + indicesQuery(termQuery("title", "title1").queryName("title1"), "test1") + .noMatchQuery(termQuery("title", "title2").queryName("title2")).queryName("indices_filter"), + termQuery("title", "title3").queryName("title3")).queryName("or"))).get(); assertHitCount(searchResponse, 3l); for (SearchHit hit : searchResponse.getHits()) { @@ -255,7 +254,7 @@ public class MatchedQueriesTests extends ElasticsearchIntegrationTest { QueryBuilder[] queries = new QueryBuilder[]{ wrapperQuery(matchQuery("content", "amet").queryName("abc").buildAsBytes().toUtf8()), - constantScoreQuery(wrapperFilter(termFilter("content", "amet").filterName("abc").buildAsBytes().toUtf8())) + constantScoreQuery(wrapperQuery(termQuery("content", "amet").queryName("abc").buildAsBytes().toUtf8())) }; for (QueryBuilder query : queries) { SearchResponse searchResponse = client().prepareSearch() diff --git a/src/test/java/org/elasticsearch/search/morelikethis/MoreLikeThisTests.java b/src/test/java/org/elasticsearch/search/morelikethis/MoreLikeThisTests.java index 664bf58c1f1..017e323bf16 100644 --- a/src/test/java/org/elasticsearch/search/morelikethis/MoreLikeThisTests.java +++ b/src/test/java/org/elasticsearch/search/morelikethis/MoreLikeThisTests.java @@ -43,7 +43,7 @@ import static org.elasticsearch.client.Requests.*; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.index.query.QueryBuilders.moreLikeThisQuery; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; import static org.hamcrest.Matchers.equalTo; @@ -107,8 +107,8 @@ public class MoreLikeThisTests extends ElasticsearchIntegrationTest { .startObject("text").field("type", "string").endObject() .endObject().endObject().endObject())); logger.info("Creating aliases alias release"); - client().admin().indices().aliases(indexAliasesRequest().addAlias("release", termFilter("text", "release"), "test")).actionGet(); - client().admin().indices().aliases(indexAliasesRequest().addAlias("beta", termFilter("text", "beta"), "test")).actionGet(); + client().admin().indices().aliases(indexAliasesRequest().addAlias("release", termQuery("text", "release"), "test")).actionGet(); + client().admin().indices().aliases(indexAliasesRequest().addAlias("beta", termQuery("text", "beta"), "test")).actionGet(); logger.info("Running Cluster Health"); assertThat(ensureGreen(), equalTo(ClusterHealthStatus.GREEN)); diff --git a/src/test/java/org/elasticsearch/search/query/ExistsMissingTests.java b/src/test/java/org/elasticsearch/search/query/ExistsMissingTests.java index b420521eaaa..c064249fa3d 100644 --- a/src/test/java/org/elasticsearch/search/query/ExistsMissingTests.java +++ b/src/test/java/org/elasticsearch/search/query/ExistsMissingTests.java @@ -27,7 +27,7 @@ import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.index.mapper.internal.FieldNamesFieldMapper; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.FilteredQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; @@ -113,7 +113,7 @@ public class ExistsMissingTests extends ElasticsearchIntegrationTest { final String fieldName = entry.getKey(); final int count = entry.getValue(); // exists - FilteredQueryBuilder query = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.existsFilter(fieldName)); + FilteredQueryBuilder query = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), QueryBuilders.existsQuery(fieldName)); SearchResponse resp = client().prepareSearch("idx").setQuery(query).execute().actionGet(); assertSearchResponse(resp); try { @@ -130,7 +130,7 @@ public class ExistsMissingTests extends ElasticsearchIntegrationTest { } // missing - resp = client().prepareSearch("idx").setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.missingFilter(fieldName))).execute().actionGet(); + resp = client().prepareSearch("idx").setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), QueryBuilders.missingQuery(fieldName))).execute().actionGet(); assertSearchResponse(resp); assertEquals(String.format(Locale.ROOT, "missing(%s, %d) mapping: %s response: %s", fieldName, count, mapping.string(), resp), numDocs - count, resp.getHits().totalHits()); } diff --git a/src/test/java/org/elasticsearch/search/query/SearchQueryTests.java b/src/test/java/org/elasticsearch/search/query/SearchQueryTests.java index e72cad5dfdd..64ea1c2f3ca 100644 --- a/src/test/java/org/elasticsearch/search/query/SearchQueryTests.java +++ b/src/test/java/org/elasticsearch/search/query/SearchQueryTests.java @@ -56,7 +56,6 @@ import java.util.concurrent.ExecutionException; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.*; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.scriptFunction; import static org.elasticsearch.test.VersionUtils.randomVersion; @@ -131,10 +130,10 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { client().prepareSearch() .setQuery(matchAllQuery()) .setPostFilter( - andFilter( - queryFilter(matchAllQuery()), - notFilter(andFilter(queryFilter(termQuery("field1", "value1")), - queryFilter(termQuery("field1", "value2")))))).get(), + andQuery( + matchAllQuery(), + notQuery(andQuery(termQuery("field1", "value1"), + termQuery("field1", "value2"))))).get(), 3l); assertHitCount( client().prepareSearch() @@ -142,11 +141,11 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { filteredQuery( boolQuery().should(termQuery("field1", "value1")).should(termQuery("field1", "value2")) .should(termQuery("field1", "value3")), - notFilter(andFilter(queryFilter(termQuery("field1", "value1")), - queryFilter(termQuery("field1", "value2")))))).get(), + notQuery(andQuery(termQuery("field1", "value1"), + termQuery("field1", "value2"))))).get(), 3l); assertHitCount( - client().prepareSearch().setQuery(matchAllQuery()).setPostFilter(notFilter(termFilter("field1", "value3"))).get(), + client().prepareSearch().setQuery(matchAllQuery()).setPostFilter(notQuery(termQuery("field1", "value3"))).get(), 2l); } @@ -223,18 +222,10 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { for (SearchHit searchHit : hits) { assertSearchHit(searchHit, hasScore(1.0f)); } - if (random.nextBoolean()) { - searchResponse = client().prepareSearch("test_1").setQuery( - boolQuery().must(matchAllQuery()).must( - constantScoreQuery(matchQuery).boost(1.0f + (random.nextBoolean()? 0.0f : random.nextFloat())))).setSize(num).get(); - hits = searchResponse.getHits(); - } else { - FilterBuilder filter = queryFilter(matchQuery); - searchResponse = client().prepareSearch("test_1").setQuery( - boolQuery().must(matchAllQuery()).must( - constantScoreQuery(filter).boost(1.0f + (random.nextBoolean()? 0.0f : random.nextFloat())))).setSize(num).get(); - hits = searchResponse.getHits(); - } + searchResponse = client().prepareSearch("test_1").setQuery( + boolQuery().must(matchAllQuery()).must( + constantScoreQuery(matchQuery).boost(1.0f + (random.nextBoolean()? 0.0f : random.nextFloat())))).setSize(num).get(); + hits = searchResponse.getHits(); assertThat(hits.totalHits(), equalTo(totalHits)); if (totalHits > 1) { float expected = hits.getAt(0).score(); @@ -650,8 +641,8 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type2", "2").setSource("field1", "value1"), client().prepareIndex("test", "type2", "3").setSource("field1", "value1")); - assertHitCount(client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), typeFilter("type1"))).get(), 2l); - assertHitCount(client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), typeFilter("type2"))).get(), 3l); + assertHitCount(client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), typeQuery("type1"))).get(), 2l); + assertHitCount(client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), typeQuery("type2"))).get(), 3l); assertHitCount(client().prepareSearch().setTypes("type1").setQuery(matchAllQuery()).get(), 2l); assertHitCount(client().prepareSearch().setTypes("type2").setQuery(matchAllQuery()).get(), 3l); @@ -660,16 +651,16 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { } @Test - public void idsFilterTestsIdIndexed() throws Exception { - idsFilterTests("not_analyzed"); + public void idsQueryTestsIdIndexed() throws Exception { + idsQueryTests("not_analyzed"); } @Test - public void idsFilterTestsIdNotIndexed() throws Exception { - idsFilterTests("no"); + public void idsQueryTestsIdNotIndexed() throws Exception { + idsQueryTests("no"); } - private void idsFilterTests(String index) throws Exception { + private void idsQueryTests(String index) throws Exception { Settings indexSettings = ImmutableSettings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.V_1_4_2.id).build(); assertAcked(client().admin().indices().prepareCreate("test").setSettings(indexSettings) .addMapping("type1", jsonBuilder().startObject().startObject("type1") @@ -680,12 +671,12 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type1", "2").setSource("field1", "value2"), client().prepareIndex("test", "type1", "3").setSource("field1", "value3")); - SearchResponse searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsFilter("type1").ids("1", "3"))).get(); + SearchResponse searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsQuery("type1").ids("1", "3"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "3"); // no type - searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsFilter().ids("1", "3"))).get(); + searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsQuery().ids("1", "3"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "3"); @@ -702,7 +693,7 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { assertHitCount(searchResponse, 0l); // repeat..., with terms - searchResponse = client().prepareSearch().setTypes("type1").setQuery(constantScoreQuery(termsFilter("_id", "1", "3"))).get(); + searchResponse = client().prepareSearch().setTypes("type1").setQuery(constantScoreQuery(termsQuery("_id", "1", "3"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "3"); } @@ -716,7 +707,7 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type1", "3").setSource("field2", "value2_3"), client().prepareIndex("test", "type1", "4").setSource("field3", "value3_4")); - assertHitCount(client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), limitFilter(2))).get(), 4l); // no-op + assertHitCount(client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), limitQuery(2))).get(), 4l); // no-op } @Test @@ -729,11 +720,11 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type1", "3").setSource(jsonBuilder().startObject().startObject("obj2").field("obj2_val", "1").endObject().field("y1", "y_1").field("field2", "value2_3").endObject()), client().prepareIndex("test", "type1", "4").setSource(jsonBuilder().startObject().startObject("obj2").field("obj2_val", "1").endObject().field("y2", "y_2").field("field3", "value3_4").endObject()) ); - SearchResponse searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), existsFilter("field1"))).get(); + SearchResponse searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), existsQuery("field1"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "2"); - searchResponse = client().prepareSearch().setQuery(constantScoreQuery(existsFilter("field1"))).get(); + searchResponse = client().prepareSearch().setQuery(constantScoreQuery(existsQuery("field1"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "2"); @@ -741,33 +732,33 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "2"); - searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), existsFilter("field2"))).get(); + searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), existsQuery("field2"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "3"); - searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), existsFilter("field3"))).get(); + searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), existsQuery("field3"))).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("4")); // wildcard check - searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), existsFilter("x*"))).get(); + searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), existsQuery("x*"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "2"); // object check - searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), existsFilter("obj1"))).get(); + searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), existsQuery("obj1"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "2"); - searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), missingFilter("field1"))).get(); + searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), missingQuery("field1"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "3", "4"); - searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), missingFilter("field1"))).get(); + searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), missingQuery("field1"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "3", "4"); - searchResponse = client().prepareSearch().setQuery(constantScoreQuery(missingFilter("field1"))).get(); + searchResponse = client().prepareSearch().setQuery(constantScoreQuery(missingQuery("field1"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "3", "4"); @@ -776,12 +767,12 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { assertSearchHits(searchResponse, "3", "4"); // wildcard check - searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), missingFilter("x*"))).get(); + searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), missingQuery("x*"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "3", "4"); // object check - searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), missingFilter("obj1"))).get(); + searchResponse = client().prepareSearch().setQuery(filteredQuery(matchAllQuery(), missingQuery("obj1"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "3", "4"); } @@ -798,7 +789,7 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { BoolQueryBuilder bool = boolQuery().must(wrapper).must(new TermQueryBuilder("field2", "value2_1")); assertHitCount(client().prepareSearch().setQuery(bool).get(), 1l); - WrapperFilterBuilder wrapperFilter = new WrapperFilterBuilder("{ \"term\" : { \"field1\" : \"value1_1\" } }"); + WrapperQueryBuilder wrapperFilter = wrapperQuery("{ \"term\" : { \"field1\" : \"value1_1\" } }"); assertHitCount(client().prepareSearch().setPostFilter(wrapperFilter).get(), 1l); } @@ -808,16 +799,16 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { ensureGreen(); client().prepareIndex("test", "type1", "1").setSource("field1", "value1").get(); refresh(); - SearchResponse searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(termsFilter("field1", "value1"))).get(); + SearchResponse searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(termsQuery("field1", "value1"))).get(); assertHitCount(searchResponse, 1l); - searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(termsFilter("field1", "value1"))).get(); + searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(termsQuery("field1", "value1"))).get(); assertHitCount(searchResponse, 1l); - searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(termsFilter("field1", "value1"))).get(); + searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(termsQuery("field1", "value1"))).get(); assertHitCount(searchResponse, 1l); - searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(termsFilter("field1", "value1"))).get(); + searchResponse = client().prepareSearch("test").setQuery(constantScoreQuery(termsQuery("field1", "value1"))).get(); assertHitCount(searchResponse, 1l); } @@ -1081,7 +1072,7 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { } @Test - public void testEmptyTermsFilter() throws Exception { + public void testEmptytermsQuery() throws Exception { assertAcked(prepareCreate("test").addMapping("type", "term", "type=string")); ensureGreen(); indexRandom(true, client().prepareIndex("test", "type", "1").setSource("term", "1"), @@ -1090,15 +1081,15 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type", "4").setSource("term", "4") ); SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("term", new String[0]))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("term", new String[0]))).get(); assertHitCount(searchResponse, 0l); - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), idsFilter())).get(); + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), idsQuery())).get(); assertHitCount(searchResponse, 0l); } @Test - public void testFieldDataTermsFilter() throws Exception { + public void testFieldDatatermsQuery() throws Exception { assertAcked(prepareCreate("test").addMapping("type", "str", "type=string", "lng", "type=long", "dbl", "type=double")); ensureGreen(); indexRandom(true, @@ -1108,60 +1099,60 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type", "4").setSource("str", "4", "lng", 4l, "dbl", 4.0d)); SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("str", "1", "4").execution("fielddata"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("str", "1", "4").execution("fielddata"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "4"); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("lng", new long[] {2, 3}).execution("fielddata"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("lng", new long[] {2, 3}).execution("fielddata"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "2", "3"); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("dbl", new double[]{2, 3}).execution("fielddata"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("dbl", new double[]{2, 3}).execution("fielddata"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "2", "3"); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("lng", new int[] {1, 3}).execution("fielddata"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("lng", new int[] {1, 3}).execution("fielddata"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "3"); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("dbl", new float[] {2, 4}).execution("fielddata"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("dbl", new float[] {2, 4}).execution("fielddata"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "2", "4"); // test partial matching searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("str", "2", "5").execution("fielddata"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("str", "2", "5").execution("fielddata"))).get(); assertNoFailures(searchResponse); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("2")); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("dbl", new double[] {2, 5}).execution("fielddata"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("dbl", new double[] {2, 5}).execution("fielddata"))).get(); assertNoFailures(searchResponse); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("2")); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("lng", new long[] {2, 5}).execution("fielddata"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("lng", new long[] {2, 5}).execution("fielddata"))).get(); assertNoFailures(searchResponse); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("2")); // test valid type, but no matching terms searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("str", "5", "6").execution("fielddata"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("str", "5", "6").execution("fielddata"))).get(); assertHitCount(searchResponse, 0l); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("dbl", new double[] {5, 6}).execution("fielddata"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("dbl", new double[] {5, 6}).execution("fielddata"))).get(); assertHitCount(searchResponse, 0l); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsFilter("lng", new long[] {5, 6}).execution("fielddata"))).get(); + .setQuery(filteredQuery(matchAllQuery(), termsQuery("lng", new long[] {5, 6}).execution("fielddata"))).get(); assertHitCount(searchResponse, 0l); } @@ -1204,62 +1195,62 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type", "4").setSource("term", "4") ); SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms")) + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms")) ).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "3"); // same as above, just on the _id... searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("_id").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms")) + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("_id").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms")) ).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "3"); // another search with same parameters... searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms")) + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms")) ).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "3"); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("2").lookupPath("terms")) + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup").lookupType("type").lookupId("2").lookupPath("terms")) ).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("2")); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("3").lookupPath("terms")) + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup").lookupType("type").lookupId("3").lookupPath("terms")) ).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "2", "4"); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("4").lookupPath("terms")) + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup").lookupType("type").lookupId("4").lookupPath("terms")) ).get(); assertHitCount(searchResponse, 0l); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup2").lookupType("type").lookupId("1").lookupPath("arr.term")) + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup2").lookupType("type").lookupId("1").lookupPath("arr.term")) ).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "3"); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup2").lookupType("type").lookupId("2").lookupPath("arr.term")) + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup2").lookupType("type").lookupId("2").lookupPath("arr.term")) ).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("2")); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup2").lookupType("type").lookupId("3").lookupPath("arr.term")) + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("term").lookupIndex("lookup2").lookupType("type").lookupId("3").lookupPath("arr.term")) ).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "2", "4"); searchResponse = client().prepareSearch("test") - .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("not_exists").lookupIndex("lookup2").lookupType("type").lookupId("3").lookupPath("arr.term")) + .setQuery(filteredQuery(matchAllQuery(), termsLookupQuery("not_exists").lookupIndex("lookup2").lookupType("type").lookupId("3").lookupPath("arr.term")) ).get(); assertHitCount(searchResponse, 0l); } @@ -1273,39 +1264,39 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { client().prepareIndex("test", "type2", "2").setSource("field1", "value2").get(); refresh(); - SearchResponse searchResponse = client().prepareSearch().setQuery(matchAllQuery()).setPostFilter(idsFilter("type1").ids("1")).get(); + SearchResponse searchResponse = client().prepareSearch().setQuery(matchAllQuery()).setPostFilter(idsQuery("type1").ids("1")).get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().hits().length, equalTo(1)); - searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsFilter("type1", "type2").ids("1", "2"))).get(); + searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsQuery("type1", "type2").ids("1", "2"))).get(); assertHitCount(searchResponse, 2l); assertThat(searchResponse.getHits().hits().length, equalTo(2)); - searchResponse = client().prepareSearch().setQuery(matchAllQuery()).setPostFilter(idsFilter().ids("1")).get(); + searchResponse = client().prepareSearch().setQuery(matchAllQuery()).setPostFilter(idsQuery().ids("1")).get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().hits().length, equalTo(1)); - searchResponse = client().prepareSearch().setQuery(matchAllQuery()).setPostFilter(idsFilter().ids("1", "2")).get(); + searchResponse = client().prepareSearch().setQuery(matchAllQuery()).setPostFilter(idsQuery().ids("1", "2")).get(); assertHitCount(searchResponse, 2l); assertThat(searchResponse.getHits().hits().length, equalTo(2)); - searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsFilter().ids("1", "2"))).get(); + searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsQuery().ids("1", "2"))).get(); assertHitCount(searchResponse, 2l); assertThat(searchResponse.getHits().hits().length, equalTo(2)); - searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsFilter("type1").ids("1", "2"))).get(); + searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsQuery("type1").ids("1", "2"))).get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().hits().length, equalTo(1)); - searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsFilter().ids("1"))).get(); + searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsQuery().ids("1"))).get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().hits().length, equalTo(1)); - searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsFilter(null).ids("1"))).get(); + searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsQuery(null).ids("1"))).get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().hits().length, equalTo(1)); - searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsFilter("type1", "type2", "type3").ids("1", "2", "3", "4"))).get(); + searchResponse = client().prepareSearch().setQuery(constantScoreQuery(idsQuery("type1", "type2", "type3").ids("1", "2", "3", "4"))).get(); assertHitCount(searchResponse, 2l); assertThat(searchResponse.getHits().hits().length, equalTo(2)); } @@ -1410,42 +1401,42 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { assertFirstHit(searchResponse, hasId("1")); logger.info("--> term filter on 1"); - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_byte", 1))).get(); + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termQuery("num_byte", 1))).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("1")); - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_short", 1))).get(); + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termQuery("num_short", 1))).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("1")); - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_integer", 1))).get(); + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termQuery("num_integer", 1))).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("1")); - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_long", 1))).get(); + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termQuery("num_long", 1))).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("1")); - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_float", 1))).get(); + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termQuery("num_float", 1))).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("1")); - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_double", 1))).get(); + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termQuery("num_double", 1))).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("1")); logger.info("--> terms filter on 1"); - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_byte", new int[]{1}))).get(); + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("num_byte", new int[]{1}))).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("1")); - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_short", new int[]{1}))).get(); + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("num_short", new int[]{1}))).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("1")); - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_integer", new int[]{1}))).get(); + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("num_integer", new int[]{1}))).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("1")); - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_long", new int[]{1}))).get(); + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("num_long", new int[]{1}))).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("1")); - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_float", new int[]{1}))).get(); + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("num_float", new int[]{1}))).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("1")); - searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_double", new int[]{1}))).get(); + searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), termsQuery("num_double", new int[]{1}))).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("1")); } @@ -1466,26 +1457,26 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { refresh(); SearchResponse searchResponse = client().prepareSearch("test").setPostFilter( - boolFilter() - .should(rangeFilter("num_long", 1, 2)) - .should(rangeFilter("num_long", 3, 4)) + boolQuery() + .should(rangeQuery("num_long").from(1).to(2)) + .should(rangeQuery("num_long").from(3).to(4)) ).get(); assertHitCount(searchResponse, 4l); // This made 2826 fail! (only with bit based filters) searchResponse = client().prepareSearch("test").setPostFilter( - boolFilter() - .should(rangeFilter("num_long", 1, 2)) - .should(rangeFilter("num_long", 3, 4)) + boolQuery() + .should(rangeQuery("num_long").from(1).to(2)) + .should(rangeQuery("num_long").from(3).to(4)) ).get(); assertHitCount(searchResponse, 4l); // This made #2979 fail! searchResponse = client().prepareSearch("test").setPostFilter( - boolFilter() - .must(termFilter("field1", "test1")) - .should(rangeFilter("num_long", 1, 2)) - .should(rangeFilter("num_long", 3, 4)) + boolQuery() + .must(termQuery("field1", "test1")) + .should(rangeQuery("num_long").from(1).to(2)) + .should(rangeQuery("num_long").from(3).to(4)) ).get(); assertHitCount(searchResponse, 2l); } @@ -1566,7 +1557,7 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { assertHitCount(response, 3); response = client().prepareSearch("test") - .setQuery(spanOrQuery().clause(spanMultiTermQueryBuilder(rangeQuery("description").from("ffa").to("foo")))) + .setQuery(spanOrQuery().clause(spanMultiTermQueryBuilder(QueryBuilders.rangeQuery("description").from("ffa").to("foo")))) .execute().actionGet(); assertHitCount(response, 3); @@ -1873,26 +1864,26 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { refresh(); SearchResponse searchResponse = client().prepareSearch("index1", "index2", "index3") - .setPostFilter(indicesFilter(termFilter("text", "value1"), "index1") - .noMatchFilter(termFilter("text", "value2"))).get(); + .setPostFilter(indicesQuery(termQuery("text", "value1"), "index1") + .noMatchQuery(termQuery("text", "value2"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "2"); //default no match filter is "all" searchResponse = client().prepareSearch("index1", "index2", "index3") - .setPostFilter(indicesFilter(termFilter("text", "value1"), "index1")).get(); + .setPostFilter(indicesQuery(termQuery("text", "value1"), "index1")).get(); assertHitCount(searchResponse, 3l); assertSearchHits(searchResponse, "1", "2", "3"); searchResponse = client().prepareSearch("index1", "index2", "index3") - .setPostFilter(indicesFilter(termFilter("text", "value1"), "index1") - .noMatchFilter("all")).get(); + .setPostFilter(indicesQuery(termQuery("text", "value1"), "index1") + .noMatchQuery("all")).get(); assertHitCount(searchResponse, 3l); assertSearchHits(searchResponse, "1", "2", "3"); searchResponse = client().prepareSearch("index1", "index2", "index3") - .setPostFilter(indicesFilter(termFilter("text", "value1"), "index1") - .noMatchFilter("none")).get(); + .setPostFilter(indicesQuery(termQuery("text", "value1"), "index1") + .noMatchQuery("none")).get(); assertHitCount(searchResponse, 1l); assertFirstHit(searchResponse, hasId("1")); } @@ -1946,7 +1937,7 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { //has_child fails if executed on "simple" index try { client().prepareSearch("simple") - .setPostFilter(hasChildFilter("child", termFilter("text", "value1"))).get(); + .setPostFilter(hasChildQuery("child", termQuery("text", "value1"))).get(); fail("Should have failed as has_child query can only be executed against parent-child types"); } catch (SearchPhaseExecutionException e) { assertThat(e.shardFailures().length, greaterThan(0)); @@ -1956,8 +1947,8 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { } SearchResponse searchResponse = client().prepareSearch("related", "simple") - .setPostFilter(indicesFilter(hasChildFilter("child", termFilter("text", "value2")), "related") - .noMatchFilter(termFilter("text", "value1"))).get(); + .setPostFilter(indicesQuery(hasChildQuery("child", termQuery("text", "value2")), "related") + .noMatchQuery(termQuery("text", "value1"))).get(); assertHitCount(searchResponse, 2l); assertSearchHits(searchResponse, "1", "2"); } @@ -2048,8 +2039,8 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { //all indices are missing SearchResponse searchResponse = client().prepareSearch().setQuery( filteredQuery(matchAllQuery(), - indicesFilter(termFilter("field", "missing"), "test1", "test2", "test3") - .noMatchFilter(termFilter("field", "match")))).get(); + indicesQuery(termQuery("field", "missing"), "test1", "test2", "test3") + .noMatchQuery(termQuery("field", "match")))).get(); assertHitCount(searchResponse, 3l); @@ -2068,8 +2059,8 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { //only one index specified, which is missing searchResponse = client().prepareSearch().setQuery( filteredQuery(matchAllQuery(), - indicesFilter(termFilter("field", "missing"), "test1") - .noMatchFilter(termFilter("field", "match")))).get(); + indicesQuery(termQuery("field", "missing"), "test1") + .noMatchQuery(termQuery("field", "match")))).get(); assertHitCount(searchResponse, 3l); @@ -2088,8 +2079,8 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { //more than one index specified, one of them is missing searchResponse = client().prepareSearch().setQuery( filteredQuery(matchAllQuery(), - indicesFilter(termFilter("field", "missing"), "index1", "test1") - .noMatchFilter(termFilter("field", "match")))).get(); + indicesQuery(termQuery("field", "missing"), "index1", "test1") + .noMatchQuery(termQuery("field", "match")))).get(); assertHitCount(searchResponse, 2l); @@ -2151,14 +2142,6 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { } } - private static FilterBuilder rangeFilter(String field, Object from, Object to) { - if (randomBoolean()) { - return FilterBuilders.rangeFilter(field).from(from).to(to); - } else { - return FilterBuilders.rangeFilter(field).from(from).to(to).setExecution("fielddata"); - } - } - @Test public void testDateProvidedAsNumber() throws ExecutionException, InterruptedException { createIndex("test"); @@ -2187,51 +2170,51 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), FilterBuilders.rangeFilter("date").from("2014-01-01T00:00:00").to("2014-01-01T00:59:00"))) + .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), QueryBuilders.rangeQuery("date").from("2014-01-01T00:00:00").to("2014-01-01T00:59:00"))) .get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getId(), is("1")); searchResponse = client().prepareSearch("test") - .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), FilterBuilders.rangeFilter("date").from("2013-12-31T23:00:00").to("2013-12-31T23:59:00"))) + .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), QueryBuilders.rangeQuery("date").from("2013-12-31T23:00:00").to("2013-12-31T23:59:00"))) .get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getId(), is("2")); searchResponse = client().prepareSearch("test") - .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), FilterBuilders.rangeFilter("date").from("2014-01-01T01:00:00").to("2014-01-01T01:59:00"))) + .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), QueryBuilders.rangeQuery("date").from("2014-01-01T01:00:00").to("2014-01-01T01:59:00"))) .get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getId(), is("3")); // We explicitly define a time zone in the from/to dates so whatever the time zone is, it won't be used searchResponse = client().prepareSearch("test") - .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), FilterBuilders.rangeFilter("date").from("2014-01-01T00:00:00Z").to("2014-01-01T00:59:00Z").timeZone("+10:00"))) + .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), QueryBuilders.rangeQuery("date").from("2014-01-01T00:00:00Z").to("2014-01-01T00:59:00Z").timeZone("+10:00"))) .get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getId(), is("1")); searchResponse = client().prepareSearch("test") - .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), FilterBuilders.rangeFilter("date").from("2013-12-31T23:00:00Z").to("2013-12-31T23:59:00Z").timeZone("+10:00"))) + .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), QueryBuilders.rangeQuery("date").from("2013-12-31T23:00:00Z").to("2013-12-31T23:59:00Z").timeZone("+10:00"))) .get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getId(), is("2")); searchResponse = client().prepareSearch("test") - .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), FilterBuilders.rangeFilter("date").from("2014-01-01T01:00:00Z").to("2014-01-01T01:59:00Z").timeZone("+10:00"))) + .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), QueryBuilders.rangeQuery("date").from("2014-01-01T01:00:00Z").to("2014-01-01T01:59:00Z").timeZone("+10:00"))) .get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getId(), is("3")); // We define a time zone to be applied to the filter and from/to have no time zone searchResponse = client().prepareSearch("test") - .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), FilterBuilders.rangeFilter("date").from("2014-01-01T03:00:00").to("2014-01-01T03:59:00").timeZone("+03:00"))) + .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), QueryBuilders.rangeQuery("date").from("2014-01-01T03:00:00").to("2014-01-01T03:59:00").timeZone("+03:00"))) .get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getId(), is("1")); searchResponse = client().prepareSearch("test") - .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), FilterBuilders.rangeFilter("date").from("2014-01-01T02:00:00").to("2014-01-01T02:59:00").timeZone("+03:00"))) + .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), QueryBuilders.rangeQuery("date").from("2014-01-01T02:00:00").to("2014-01-01T02:59:00").timeZone("+03:00"))) .get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getId(), is("2")); searchResponse = client().prepareSearch("test") - .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), FilterBuilders.rangeFilter("date").from("2014-01-01T04:00:00").to("2014-01-01T04:59:00").timeZone("+03:00"))) + .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), QueryBuilders.rangeQuery("date").from("2014-01-01T04:00:00").to("2014-01-01T04:59:00").timeZone("+03:00"))) .get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getId(), is("3")); @@ -2239,7 +2222,7 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { // When we use long values, it means we have ms since epoch UTC based so we don't apply any transformation try { client().prepareSearch("test") - .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), FilterBuilders.rangeFilter("date").from(1388534400000L).to(1388537940999L).timeZone("+01:00"))) + .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), QueryBuilders.rangeQuery("date").from(1388534400000L).to(1388537940999L).timeZone("+01:00"))) .get(); fail("A Range Filter using ms since epoch with a TimeZone should raise a QueryParsingException"); } catch (SearchPhaseExecutionException e) { @@ -2247,13 +2230,13 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { } searchResponse = client().prepareSearch("test") - .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), FilterBuilders.rangeFilter("date").from("2014-01-01").to("2014-01-01T00:59:00").timeZone("-01:00"))) + .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), QueryBuilders.rangeQuery("date").from("2014-01-01").to("2014-01-01T00:59:00").timeZone("-01:00"))) .get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getId(), is("3")); searchResponse = client().prepareSearch("test") - .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), FilterBuilders.rangeFilter("date").from("now/d-1d").timeZone("+01:00"))) + .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), QueryBuilders.rangeQuery("date").from("now/d-1d").timeZone("+01:00"))) .get(); assertHitCount(searchResponse, 1l); assertThat(searchResponse.getHits().getAt(0).getId(), is("4")); @@ -2261,7 +2244,7 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { // A Range Filter on a numeric field with a TimeZone should raise an exception try { client().prepareSearch("test") - .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), FilterBuilders.rangeFilter("num").from("0").to("4").timeZone("-01:00"))) + .setQuery(QueryBuilders.filteredQuery(matchAllQuery(), QueryBuilders.rangeQuery("num").from("0").to("4").timeZone("-01:00"))) .get(); fail("A Range Filter on a numeric field with a TimeZone should raise a QueryParsingException"); } catch (SearchPhaseExecutionException e) { @@ -2458,10 +2441,10 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { SearchResponse one = client().prepareSearch() .setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.filteredQuery(QueryBuilders.termQuery("field1", query), - FilterBuilders.termFilter("field1", filter)))).setSize(numDocs).execute().actionGet(); + QueryBuilders.termQuery("field1", filter)))).setSize(numDocs).execute().actionGet(); SearchResponse other = client().prepareSearch() .setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.filteredQuery(QueryBuilders.termQuery("field1", filter), - FilterBuilders.termFilter("field1", query)))).setSize(numDocs).execute().actionGet(); + QueryBuilders.termQuery("field1", query)))).setSize(numDocs).execute().actionGet(); Set oneIds = new HashSet<>(); for (SearchHit hit : one.getHits().hits()) { @@ -2485,7 +2468,7 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { indexRandom(true, client().prepareIndex("test", "type1", "1").setSource("field1", "value1")); SearchResponse response = client().prepareSearch() .setQuery(QueryBuilders.filteredQuery(null, - FilterBuilders.termFilter("field1", "value1"))).get(); + QueryBuilders.termQuery("field1", "value1"))).get(); assertSearchResponse(response); assertHitCount(response, 1l); } diff --git a/src/test/java/org/elasticsearch/search/scriptfilter/ScriptFilterSearchTests.java b/src/test/java/org/elasticsearch/search/scriptfilter/ScriptFilterSearchTests.java index 286e7f72af8..ad6db550564 100644 --- a/src/test/java/org/elasticsearch/search/scriptfilter/ScriptFilterSearchTests.java +++ b/src/test/java/org/elasticsearch/search/scriptfilter/ScriptFilterSearchTests.java @@ -32,7 +32,7 @@ import org.junit.Test; import java.util.concurrent.atomic.AtomicInteger; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.scriptFilter; +import static org.elasticsearch.index.query.QueryBuilders.scriptQuery; import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.hamcrest.Matchers.equalTo; @@ -70,7 +70,7 @@ public class ScriptFilterSearchTests extends ElasticsearchIntegrationTest { logger.info("running doc['num1'].value > 1"); SearchResponse response = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), scriptFilter("doc['num1'].value > 1"))) + .setQuery(filteredQuery(matchAllQuery(), scriptQuery("doc['num1'].value > 1"))) .addSort("num1", SortOrder.ASC) .addScriptField("sNum1", "doc['num1'].value") .execute().actionGet(); @@ -83,7 +83,7 @@ public class ScriptFilterSearchTests extends ElasticsearchIntegrationTest { logger.info("running doc['num1'].value > param1"); response = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), scriptFilter("doc['num1'].value > param1").addParam("param1", 2))) + .setQuery(filteredQuery(matchAllQuery(), scriptQuery("doc['num1'].value > param1").addParam("param1", 2))) .addSort("num1", SortOrder.ASC) .addScriptField("sNum1", "doc['num1'].value") .execute().actionGet(); @@ -94,7 +94,7 @@ public class ScriptFilterSearchTests extends ElasticsearchIntegrationTest { logger.info("running doc['num1'].value > param1"); response = client().prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), scriptFilter("doc['num1'].value > param1").addParam("param1", -1))) + .setQuery(filteredQuery(matchAllQuery(), scriptQuery("doc['num1'].value > param1").addParam("param1", -1))) .addSort("num1", SortOrder.ASC) .addScriptField("sNum1", "doc['num1'].value") .execute().actionGet(); diff --git a/src/test/java/org/elasticsearch/search/sort/SimpleSortTests.java b/src/test/java/org/elasticsearch/search/sort/SimpleSortTests.java index c048e1f5ed1..fb3c9ec4858 100644 --- a/src/test/java/org/elasticsearch/search/sort/SimpleSortTests.java +++ b/src/test/java/org/elasticsearch/search/sort/SimpleSortTests.java @@ -24,7 +24,6 @@ import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.TestUtil; import org.apache.lucene.util.UnicodeUtil; -import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.admin.indices.alias.Alias; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchPhaseExecutionException; @@ -40,7 +39,6 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.fielddata.IndexFieldData; import org.elasticsearch.index.mapper.Uid; -import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; import org.elasticsearch.search.SearchHit; @@ -51,16 +49,44 @@ import org.hamcrest.Matchers; import org.junit.Test; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; import java.util.Map.Entry; +import java.util.Random; +import java.util.Set; +import java.util.TreeMap; import java.util.concurrent.ExecutionException; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.scriptFunction; import static org.elasticsearch.search.sort.SortBuilders.fieldSort; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; -import static org.hamcrest.Matchers.*; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFirstHit; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertOrderedSearchHits; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSecondHit; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSortValues; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.hasId; +import static org.hamcrest.Matchers.closeTo; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** @@ -131,8 +157,8 @@ public class SimpleSortTests extends ElasticsearchIntegrationTest { indexRandom(true, builders); ensureYellow(); SearchResponse allDocsResponse = client().prepareSearch().setQuery(QueryBuilders.filteredQuery(matchAllQuery(), - FilterBuilders.boolFilter().must(FilterBuilders.termFilter("foo", "bar"), - FilterBuilders.rangeFilter("timeUpdated").gte("2014/0" + randomIntBetween(1, 7) + "/01")))) + QueryBuilders.boolQuery().must(QueryBuilders.termQuery("foo", "bar")).must( + QueryBuilders.rangeQuery("timeUpdated").gte("2014/0" + randomIntBetween(1, 7) + "/01")))) .addSort(new FieldSortBuilder("timeUpdated").order(SortOrder.ASC).unmappedType("date")) .setSize(docs).get(); assertSearchResponse(allDocsResponse); @@ -140,8 +166,8 @@ public class SimpleSortTests extends ElasticsearchIntegrationTest { final int numiters = randomIntBetween(1, 20); for (int i = 0; i < numiters; i++) { SearchResponse searchResponse = client().prepareSearch().setQuery(QueryBuilders.filteredQuery(matchAllQuery(), - FilterBuilders.boolFilter().must(FilterBuilders.termFilter("foo", "bar"), - FilterBuilders.rangeFilter("timeUpdated").gte("2014/" + String.format(Locale.ROOT, "%02d", randomIntBetween(1, 7)) + "/01")))) + QueryBuilders.boolQuery().must(QueryBuilders.termQuery("foo", "bar")).must( + QueryBuilders.rangeQuery("timeUpdated").gte("2014/" + String.format(Locale.ROOT, "%02d", randomIntBetween(1, 7)) + "/01")))) .addSort(new FieldSortBuilder("timeUpdated").order(SortOrder.ASC).unmappedType("date")) .setSize(scaledRandomIntBetween(1, docs)).get(); assertSearchResponse(searchResponse); @@ -272,7 +298,7 @@ public class SimpleSortTests extends ElasticsearchIntegrationTest { if (!sparseBytes.isEmpty()) { int size = between(1, sparseBytes.size()); SearchResponse searchResponse = client().prepareSearch().setQuery(matchAllQuery()) - .setPostFilter(FilterBuilders.existsFilter("sparse_bytes")).setSize(size).addSort("sparse_bytes", SortOrder.ASC).execute() + .setPostFilter(QueryBuilders.existsQuery("sparse_bytes")).setSize(size).addSort("sparse_bytes", SortOrder.ASC).execute() .actionGet(); assertNoFailures(searchResponse); assertThat(searchResponse.getHits().getTotalHits(), equalTo((long) sparseBytes.size())); diff --git a/src/test/java/org/elasticsearch/search/timeout/SearchTimeoutTests.java b/src/test/java/org/elasticsearch/search/timeout/SearchTimeoutTests.java index 2ef5d279c10..9b2c601864d 100644 --- a/src/test/java/org/elasticsearch/search/timeout/SearchTimeoutTests.java +++ b/src/test/java/org/elasticsearch/search/timeout/SearchTimeoutTests.java @@ -25,7 +25,7 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.junit.Test; -import static org.elasticsearch.index.query.FilterBuilders.scriptFilter; +import static org.elasticsearch.index.query.QueryBuilders.scriptQuery; import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.hamcrest.Matchers.equalTo; @@ -46,7 +46,7 @@ public class SearchTimeoutTests extends ElasticsearchIntegrationTest { SearchResponse searchResponse = client().prepareSearch("test") .setTimeout("10ms") - .setQuery(filteredQuery(matchAllQuery(), scriptFilter("Thread.sleep(500); return true;"))) + .setQuery(filteredQuery(matchAllQuery(), scriptQuery("Thread.sleep(500); return true;"))) .execute().actionGet(); assertThat(searchResponse.isTimedOut(), equalTo(true)); } diff --git a/src/test/java/org/elasticsearch/stresstest/gcbehavior/FilterCacheGcStress.java b/src/test/java/org/elasticsearch/stresstest/gcbehavior/FilterCacheGcStress.java index cea41990668..9fbf44b79c1 100644 --- a/src/test/java/org/elasticsearch/stresstest/gcbehavior/FilterCacheGcStress.java +++ b/src/test/java/org/elasticsearch/stresstest/gcbehavior/FilterCacheGcStress.java @@ -27,7 +27,7 @@ import org.elasticsearch.node.NodeBuilder; import java.util.concurrent.atomic.AtomicBoolean; -import static org.elasticsearch.index.query.FilterBuilders.rangeFilter; +import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; @@ -60,7 +60,7 @@ public class FilterCacheGcStress { public void run() { while (!stop.get()) { client.prepareSearch() - .setQuery(filteredQuery(matchAllQuery(), rangeFilter("field").from(System.currentTimeMillis() - 1000000))) + .setQuery(filteredQuery(matchAllQuery(), rangeQuery("field").from(System.currentTimeMillis() - 1000000))) .execute().actionGet(); } } diff --git a/src/test/java/org/elasticsearch/stresstest/refresh/RefreshStressTest1.java b/src/test/java/org/elasticsearch/stresstest/refresh/RefreshStressTest1.java index 933fdbc9d2f..5ff8506fc9a 100644 --- a/src/test/java/org/elasticsearch/stresstest/refresh/RefreshStressTest1.java +++ b/src/test/java/org/elasticsearch/stresstest/refresh/RefreshStressTest1.java @@ -22,7 +22,7 @@ package org.elasticsearch.stresstest.refresh; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.ImmutableSettings; -import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; @@ -68,16 +68,16 @@ public class RefreshStressTest1 { // Thread.sleep(100); System.out.println("searching " + loop); - SearchResponse result = client.prepareSearch(indexName).setPostFilter(FilterBuilders.termFilter("name", name)).execute().actionGet(); + SearchResponse result = client.prepareSearch(indexName).setPostFilter(QueryBuilders.termQuery("name", name)).execute().actionGet(); if (result.getHits().hits().length != 1) { for (int i = 1; i <= 100; i++) { System.out.println("retry " + loop + ", " + i + ", previous total hits: " + result.getHits().getTotalHits()); client.admin().indices().prepareRefresh(indexName).execute().actionGet(); Thread.sleep(100); - result = client.prepareSearch(indexName).setPostFilter(FilterBuilders.termFilter("name", name)).execute().actionGet(); + result = client.prepareSearch(indexName).setPostFilter(QueryBuilders.termQuery("name", name)).execute().actionGet(); if (result.getHits().hits().length == 1) { client.admin().indices().prepareRefresh(indexName).execute().actionGet(); - result = client.prepareSearch(indexName).setPostFilter(FilterBuilders.termFilter("name", name)).execute().actionGet(); + result = client.prepareSearch(indexName).setPostFilter(QueryBuilders.termQuery("name", name)).execute().actionGet(); throw new RuntimeException("Record found after " + (i * 100) + " ms, second go: " + result.getHits().hits().length); } else if (i == 100) { if (client.prepareGet(indexName, typeName, id).execute().actionGet().isExists()) diff --git a/src/test/java/org/elasticsearch/test/TestSearchContext.java b/src/test/java/org/elasticsearch/test/TestSearchContext.java index bcfa48a5813..53a938a1378 100644 --- a/src/test/java/org/elasticsearch/test/TestSearchContext.java +++ b/src/test/java/org/elasticsearch/test/TestSearchContext.java @@ -23,10 +23,10 @@ import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.util.Counter; -import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.cache.recycler.PageCacheRecycler; import org.elasticsearch.common.util.BigArrays; +import org.elasticsearch.index.IndexService; import org.elasticsearch.index.analysis.AnalysisService; import org.elasticsearch.index.cache.bitset.BitsetFilterCache; import org.elasticsearch.index.cache.filter.FilterCache; @@ -35,9 +35,7 @@ import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.FieldMappers; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.query.IndexQueryParserService; -import org.elasticsearch.index.query.ParsedFilter; import org.elasticsearch.index.query.ParsedQuery; -import org.elasticsearch.index.IndexService; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.similarity.SimilarityService; import org.elasticsearch.script.ScriptService; @@ -369,12 +367,12 @@ public class TestSearchContext extends SearchContext { } @Override - public SearchContext parsedPostFilter(ParsedFilter postFilter) { + public SearchContext parsedPostFilter(ParsedQuery postFilter) { return null; } @Override - public ParsedFilter parsedPostFilter() { + public ParsedQuery parsedPostFilter() { return null; } diff --git a/src/test/java/org/elasticsearch/validate/SimpleValidateQueryTests.java b/src/test/java/org/elasticsearch/validate/SimpleValidateQueryTests.java index b1cc5938c41..3c006cdfdfb 100644 --- a/src/test/java/org/elasticsearch/validate/SimpleValidateQueryTests.java +++ b/src/test/java/org/elasticsearch/validate/SimpleValidateQueryTests.java @@ -27,7 +27,6 @@ import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.indices.IndexMissingException; @@ -167,7 +166,7 @@ public class SimpleValidateQueryTests extends ElasticsearchIntegrationTest { public void explainFilteredAlias() { assertAcked(prepareCreate("test") .addMapping("test", "field", "type=string") - .addAlias(new Alias("alias").filter(FilterBuilders.termFilter("field", "value1")))); + .addAlias(new Alias("alias").filter(QueryBuilders.termQuery("field", "value1")))); ensureGreen(); ValidateQueryResponse validateQueryResponse = client().admin().indices().prepareValidateQuery("alias")