Vespa accepts unstructured human input and structured queries for application logic separately,
then combines them into a single data structure for executing.
Human input is parsed heuristically, while application queries are formulated in YQL.
Important:
There is no way to query for a field that is not set
/ equals null or NaN.
Work around using a "magic" value (like MAXINT) that is not normally used in the documents.
select
select is the list of summary fields requested
(a field with the summary index attribute).
Vespa will hide other fields in the matching documents.
The above explicitly requests the fields "price" and "isbn" (from all sources).
To request all fields, use an asterisk as field selection:
select*fromsources*wheretitlecontains"madonna"
from sources
from sources specifies which content
sources to query. Example:
select*frommusicwheretitlecontains"madonna"
queries all document types in the music content cluster or federation source. Query in:
all sources
select … from sources * where …
a set of sources
select … from sources source1, source2 where …
a single source
select … from source1 where …
a document type (schema) from a source
select … from source1.schema1 where …
In other words, sources is used for querying some or all sources.
If only a single source is queried, the sources keyword can be dropped.
Specifying a document type (schema) with clustername.schemaname is also valid.
You can also restrict the query to one document type by using the
model.restrict URL parameter.
where
The where clause is a tree of operators:
numeric
The following numeric operators are available:
= < > <= >=.
In addition to that, the range operator can be used for numeric fields.
where500>=price
range
The range operator range(field, lower bound, upper bound) is supported for numeric and string fields. On numeric fields, it uses the intuitive ordering of numbers, and on string fields, it uses the lexicographical order.
Support for string fields available since Vespa 8.755.13
.
Numbers must be in the signed 32-bit range.
Input 64-bit signed numbers using L as suffix.
whererange(numeric_field_name, 0, 5000000000L)
When used with a string field, the string bounds have to be enclosed in (single or double) quotes.
whererange(string_field_name, "A", "C")
One can also use the strings -Infinity or Infinity
as the lower or upper bound, respectively, to express unbounded ranges.
Note that these strings must not be enclosed in quotes:
where (range(year, 2000, Infinity))
An all-encompassing numeric range matches every document that has a value set for the field.
This is a way to select the documents where a numeric field is present:
whererange(size, -Infinity, Infinity)
Important:
This does not work for single-value string fields as these
represent absent values by the empty string. Hence, this would match all documents regardless of whether
a value for the field was set or not.
Used for capped range search.
The range() query operator with hitLimit can be used to efficiently implement
top-k selection for ranking a subset of the documents in the index.
See
example and use cases.
The weightedset field does not support filtering on weight.
Solve this using the map type and
sameElement query operator -
see example.
boolean
The boolean operator is: =
wherealive=true
contains
The right-hand side argument of the contains operator is either a string literal,
or a function, like phrase.
contains is the basic building block for text matching.
The kind of matching
to be done depends on the field settings in the schema.
near() matches if all argument terms occur within the specified distance,
in any order. Negative terms (prefixed with !) exclude matches where those terms
appear within the exclusion distance.
Negative terms must come after all positive terms.
For multi-value fields, setting element-gap for the field in the rank profile enables distance calculation between adjacent elements.
Features below near() and onear() are filtered based on the spans for the operator match before they are exposed to the ranking features. Given the query
textcontains ({distance:1}near("a","b"))
and two documents.
The text field in the first document is "a a a a a a b b b b b b". The spans for the near match are [[5,6]]. Only the last occurrence of "a" and the first occurrence of "b" are kept.
The text field in the second document is "a b c a b c a b c a b c". The spans for the near match are [[0,1],[3,4],[6,7],[9,10]]. All occurrences of "a" and "b" are kept.
onear
onear() (ordered near) is like near(),
but requires terms to appear in the same order as specified in the query.
With distance set to (number of terms - 1), onear() is equivalent to phrase().
Negative terms must come after all positive terms.
For multi-value fields, setting element-gap for the field in the rank profile enables distance calculation between adjacent elements.
sameElement
The sameElement() operator lets you denote conditions that must match within the
same element in multivalue fields containing structs or strings.
By default, sameElement uses AND to combine the conditions: All the conditions
must match in the same element to produce a match.
Usage examples for the sameElement() operator:
array-of-struct fields
For example, given the struct and array of this struct
to return all documents that have a Joe Smith born before 1940 keyed as a 'father'.
array-of-string fields
sameElement() may also be used to search array of string fields. Supported query operators
inside sameElement() are and, equiv,
near, onear, or, rank and phrase.
and can be used with !.
For example, given the field
field chunks typearray<string>{indexing:index|summary}
Features inside sameElement() for indexed fields are filtered based on the matching elements, e.g.,
elementwise(bm25(descriptions),x,double) will only
contain tensor cells based on the matching elements.
array fields at specific indices
Use the elementFilter annotation
to restrict matching to specific element indices.
For example, given a field my_numbers type array<int>:
This only matches the element at index 2 in the array field.
Multiple indices can be given: {elementFilter:[0, 2, 5]}.
A shorthand form is also available:
wheremy_numbers[2] =42
The shorthand form only supports a single index.
Use the elementFilter annotation to match multiple indices.
mapMatch
Available since Vespa 8.773.18
.
The mapMatch() operator represents a restricted variant of the sameElement()
operator for searching map-like fields.
Map-like fields are fields of type map
and fast-search map fields, where
the latter can only be searched via the mapMatch() operator.
In contrast to the sameElement() operator,
the mapMatch() always takes two arguments and is limited in which
operators can be used inside of it:
The first argument has to use key with
to return all documents that have a 'price' between 0 and 99.
alternatives
The alternatives operator is used to provide multiple variants of a token at the same
position in the query. The token alternatives are given with a normalized exactness score denoting the extent to
which they mean "the same thing" as the first alternative.
The query will match documents containing any of the alternatives given. The exactness score is reflected
in some rank features, such that it is possible to rank more exact matches over less exact ones.
Use 1.0 as the exactness of all alternatives if exactness information is not available or appropriate.
Prefer alternatives to equiv when the purpose is to express alternative forms of a single token.
equiv
For cases where two terms in the same field should produce exactly the same behavior when matched,
the equiv() operator can be used. This behaves like a special case of or.
wherefieldNamecontainsequiv("A","B")
The matching logic of equiv is the same as OR,
and an OR does not have the limitations that EQUIV does (below).
The difference is in how matches are visible to ranking functions.
All words that are children of an OR count for ranking, while with
EQUIV, they look like a single word to ranking:
Counts as only +1 for queryTermCount
Counts as 1 word for completeness measures
Proximity will not discriminate different words inside the EQUIV
Connectivity can be set between the entire EQUIV and the word before and after
Items inside the EQUIV are not directly visible to ranking features,
so weight and connectivity on those will have no effect
Limitations on how equiv can be used in a query:
equiv may not appear inside a phrase
It may only contain TermItem and PhraseItem instances.
Operators like and cannot be placed inside equiv
PhraseItems inside equiv will rank like as if they have size 1
Number of characters that are considered frozen,
so the fuzzy match will be performed only with the suffix left.
Default is 0 (i.e. fuzzy will match across whole query)
If true, a string is considered a match when it's possible to transform a
prefix of the candidate string to the query string using at most maxEditDistance
edits. See fuzzy prefix match.
Default is false, which means that the entire string is considered.
Important:
Only string attribute
fields in documents are supported (single, array or weightedset).
Matching is optimized internally when maxEditDistance is 1 or 2.
Setting prefixLength greater than 0
narrows the match for the fast-search,
greatly reducing the number of terms that must be considered.
matches
Regular expression match is supported using
posix extended syntax,
with the limitation that it is case-insensitive.
Example matching both madonna, madona and with any number of ns:
Important:
Only attribute
fields in documents is supported.
It is not optimized for performance.
Having a prefix using the ^ will be faster than not having one.
Additionally, fields that serve as both attributes and indexes are not compatible.
text
text() accepts any text and tokenizes it into a set of tokens to be searched
in a given field or fieldSet.
By default, the tokens are searched with a weakAnd operator.
You can override the default behavior via annotations: text() supports the same
annotations as userInput().
userInput() parses text from end users or models that may contain query syntax
for choosing the fields to search, specifying phrases and negative terms etc.
Since the query in userInput can specify fields, there is no "contains field"
prefix before the userInput operator.
The first, and only the first, argument of the rank() function
determines whether a document is a match,
but all arguments are used for calculating rank features. The rank operator
is useful for boosting documents based on the presence of certain terms without impacting matching or retrieval logic.
It's also useful in hybrid search use cases. See blog post
for usage examples. For example, retrieve using the nearestNeighbor query operator
as the first argument and have matching features calculated for the other arguments.
Using labeled(subQuery, "mylabel", 4.25) wraps an arbitrary sub-query with a label
"mylabel" and score. If the sub-query matches a document, the score (4.25 in this example)
can be picked up by ranking expressions using the
itemRawScore
rank feature.
Available since Vespa 8.743.16
.
Typically used together with the rank operator, like this:
This is similar to Lucene's ConstantScoreQuery,
often used in Elasticsearch/OpenSearch through
function_score or in Solr with ^= query syntax.
in
The in operator is used to match a set of values in an integer or string field.
A document is considered a match when at least one of the values matches the content of the field.
This is an optimized shorthand for multiple OR conditions, and is similar to the IN operator in SQL.
Available since Vespa 8.293.15
. Example:
Where string_field is a field with match:word.
There is no linguistic processing like tokenization or stemming
of the string values used in the in operator except lowercasing. See string match.
field string_field typestring{indexing:summary|index# or attributematch: wordrank:filter
attribute:fast-search# if attribute}
Using the in operator against string fields with match:text will cause recall issues because
the field contents will be tokenized during indexing while the in operator does not tokenize the values.
The argument before in is the name of the field or fieldset to search.
The argument after in is a comma-separated list of values, enclosed in parentheses.
String values must be single or double-quoted if passed inline in YQL
For multi-value fields (like arrays), the in operator works by checking if any element in the array matches any of the values in the set.
This is similar to SQL's IN operator but more streamlined for array comparisons. Example:
whereinteger_array_fieldin (10, 20, 30)
If integer_array_field = [5, 10, 15], it will match because 10 is in the array.
Similarly, if integer_array_field = [20, 25, 30], it will match because both 20 and 30 are in the array.
For faster query parsing use parameter substitution
to submit the values as an additional request parameter.
Quoting of string values are optional. Example:
Important:
When using the in operator with an attribute field,
set fast-search and rank: filter
for best possible performance. Always use match:word for string fields.
dotProduct
dotProduct calculates the dot product between the weighted set
in the query and a weighted set field in the document as its rank score contribution:
A normal use case is a collection of weighted tokens produced by an algorithm,
to match against a corpus containing weighted tokens
produced by another algorithm in order to implement personalized content exploration.
See example usage of dotProduct
in
practical performance guide
.
Keys must be single or double-quoted if passed inline in YQL -
alternatively, use parameter substitution
to submit the weighted set with a simple format for faster query parsing -
example: where dotProduct(description, @myterms).
Field type
Weighted set attribute with fast-search. Note: Also supported for regular attribute or
index fields, but then with much weaker performance).
Query model
Weighted set with {token, weight} pairs
Matching
Documents where the weighted set field contains at least one of the tokens in the query.
Ranking
Dot product score between the weights of the matched query tokens and field tokens.
This score is available using
rawScore or
itemRawScore
rank features.
When using weightedSet to search a field,
all tokens present in the searched field will be matched against the weighted set in the query.
This means that using a weighted set to search a single-value attribute field
will have similar semantics to using a normal term to search a weighted set field.
The low-level matching information resulting from matching a document with a weighted set in the query
will contain the weights of all the matched tokens in descending order.
Each matched weight will be represented as a standard occurrence on position 0 in element 0.
whereweightedSet(description, {"a":1, "b":2})
weightedSet has similar semantics to equiv,
as it acts as a single term in the query.
However, the restriction dictating that it contains a collection of weighted tokens directly
enables specific back-end optimizations that improves performance
for large sets of tokens compared to using the generic equiv or or operators.
Keys must be single or double-quoted if passed inline in YQL -
alternatively, use parameter substitution
to submit the weighted set with a simple format for faster query parsing -
example: where weightedSet(description, @myterms).
Field type
Singlevalue or multivalue attribute or index field.
(Note: Most use cases operates on a single value field).
Query model
Weighted set with {token, weight} pairs.
Matching
Documents where the field contains at least one of the tokens in the query.
For filtering use cases we recommend using the in operator instead,
as it is simpler to use and has slightly better performance.
Ranking
The operator will act as a single term in the back-end.
The query term weight is the weight assigned to the operator itself
and the match weight is the largest weight among matching tokens from the weighted set.
This operator does not produce a raw score.
Due to better ranking and performance we recommend using dotProduct instead.
wand can be used to search for documents
where weighted tokens in a field matches a subset of weighted tokens in the query.
At the same time, it internally calculates the dot product between token weights in the query and the field.
wand is guaranteed to return the top-k hits according to its internal dot product rank score.
It is an operator that scales adaptively from or to and.
Note that total hit count becomes inaccurate when using wand.
wand optimizes the performance of using multiple threads per search in the backend,
and is also called Parallel Wand.
wand also allows numeric arguments, then the search argument is an array of arrays of length two.
In each pair, the first number is the search term, the second its weight:
wherewand(description, [[11,1], [37,2]])
Keys must be single or double-quoted if passed inline in YQL -
alternatively, use parameter substitution
to submit the weighted set with a simple format for faster query parsing -
example: where wand(description, @myterms).
Weighted set attribute with fast-search.
Note: Also supported for regular attribute or index fields,
but then with much weaker performance).
Query model
Weighted set with {token, weight} pairs.
Matching
Documents where the weighted set field contains at least one of the tokens in the query
and where the internal dot product score for this document,
is larger than the worst among the current top-k best hits.
This means that more than top-k documents are matched and returned for ranking.
It also means that many documents are skipped,
even they match several tokens in the query because the dot product score is too low.
This skipping makes wand faster than dotProduct in some cases.
Ranking
Dot product score between the weights of the matched query tokens and field tokens.
This score is available using
rawScore or
itemRawScore
rank features.
Note that the top-k best hits are only guaranteed to be returned
when using this internal score as the final ranking expression.
weakAnd is sometimes called Vespa Wand.
Unlike wand, it accepts arbitrary word matches (across arbitrary fields) as arguments.
Only a limited number of documents are returned for ranking (default is 100),
but it does not guarantee to return the best k hits.
This function can be seen as an optimized or:
Wanted number of hits exposed to the first-phase ranking function per content node.
Prefer using totalTargetHits over this.
where ({totaltargetHits: 7}weakAnd(acontains"A", bcontains"B"))
Unlike wand, weakAnd can be used
to search across several fields of various types,
but it does NOT guarantee to return the top-k best number of hits.
It can however be combined with any ranking expression.
Keep in mind that this expression should correlate with its simple internal ranking score
that uses query term weight and inverse document frequency for matching terms.
Multiple fields of all types (both attribute and index).
Query model
Arbitrary number of query items searching across different fields.
Matching
Documents that matches at least one of the tokens in the query
and where the internal operator score for this document
is larger than the worst among the current top-k best hits.
As with wand, this means that typically more than top-k documents are matched
and a lot of documents are skipped.
Ranking
Internal ranking score based on query term weight
and inverse document frequency for matching terms to find the top-k hits.
This score is currently not available to the ranking framework.
Matching terms are exposed to the ranking framework
(same as when using and or or),
so an arbitrary ranking expression can be used in combination with this operator.
Note that the ranking expression used should correlate with this internal ranking score.
bm25,
nativeFieldMatch and
nativeDotProduct
rank features are good starting points.
geoLocation matches a position
inside a geographical circle, specified as latitude, longitude, and a maximum distance (radius).
See also geoBoundingBox.
Example:
In this example we search for documents near 63.5° north, 10.5° east,
and within a 200 km radius.
So a document with a "myfieldname" position in Trondheim, Norway at
N63°25'47;E10°23'36 would match.
The first parameter is the name of the attribute field.
The second parameter is the latitude (positive for north, negative for south).
The third parameter is the longitude (positive for east, negative for west).
The fourth parameter must be a string specifying the radius and its units,
where the supported units/suffixes include "km", "m" (abbr. for meters), "miles", "mi" (abbr. for miles),
"deg" (abbr. for degrees) and "d" (contextual abbr. for degrees).
The "deg" / "d" unit / suffix gives radius the same units as latitude.
Any negative number for radius (e.g. "-1 m") is interpreted as an "infinite" radius,
letting any geographical position at all match the geoLocation operator.
The position attribute in the schema could look like:
field myfieldname typeposition{indexing:attribute|summary}
Arrays of positions are also possible:
field myfieldname typearray<position>{indexing:attribute}
geoBoundingBox requires a position
to be inside a geographical rectangle; specified as 4 numbers (in degrees).
The 4 numbers must be in a specific order:
south-western corner (minimum latitude, minimum longitude)
followed by
north-eastern corner (maximum latitude, maximum longitude).
Examples:
In the first example we search for documents inside a rectangular map view around
Trondheim, Norway.
So a document with a "myfieldname" position at
63°25'50"N 10°23'42"E
would match.
The second example surrounds
Rio de Janeiro, Brazil.
The first parameter is the name of the attribute field.
The 2nd parameter is the minimum (southern) latitude (positive for north, negative for south).
The 3rd parameter is the minimum (western) longitude (positive for east, negative for west).
The 4th parameter is the maximum (northern) latitude (positive for north, negative for south).
The 5th parameter is the maximum (eastern) longitude (positive for east, negative for west).
See the geoLocation operator for more details about positions.
Note that there is no ranking contribution from this operator; if you want to get
the distance to the center of the box, you need an additional geoLocation item
with that point.
Properties:
Field type
position attribute (single-valued or array).
Query parameters
Field name, southern, western, northern, eastern limits.
Matching
Returns documents inside the given geo bounding box.
nearestNeighbor matches the top-k nearest neighbors in a multidimensional vector space.
Points in the vector space are specified as
tensors with one indexed dimension,
where the size of that dimension is equal to the dimensionality of the vector space.
The document vectors are stored in a
tensor field attribute,
and the query vector is sent with the query request.
The following tensor field types are supported:
Single vector per document: Tensor type with one indexed dimension.
Example: tensor<float>(x[3])
Multiple vectors per document: Tensor type with one or more mapped dimensions and one indexed dimension.
Examples: tensor<float>(m{},x[3]), tensor<float>(m{},n{},x[3])
Euclidean distance is used as the default
distance metric
and the exact nearest neighbors are returned.
When storing multiple vectors per document, the vector that is closest to the query vector
is used when calculating the distance between the document and the query.
If an HNSW index is specified on the tensor field,
the approximate nearest neighbors are returned. Example:
where ({totaltargetHits: 10}nearestNeighbor(doc_vector, query_vector))&input.query(query_vector)=[3,5,7]&ranking=semantic
In this example we search for the top 10 nearest neighbors in a 3-dimensional vector space.
totalTargetHits specifies the top-k nearest neighbors to expose to a user defined semanticrank profile. The totalTargetHits annotation is required.
The first parameter of nearestNeighbor is the name of the tensor field attribute
containing the document vectors (doc_vector).
The second parameter is the name of the tensor sent with the query request (query_vector).
Specifying query_vector as the name means the query request must set this tensor as
input.query(query_vector) - see the reference.
The tensor type of the input query vector must be defined in the rank profile:
Specifies the number of hits nearestNeighbor
should expose to ranking in total over the content
nodes evaluating the query. Note that more or less hits may actually be produced.
Setting target hits is required.
Specifies the minimum target hits to produce in this nearest neighbor operator.
The default value is 100. Exploring too little in a graph leads to bad quality,
and this parameter protects against that when totalTargetHits leads to some node with
little content otherwise getting a low targetHits.
The optional approximate annotation may be set to false
to not use an approximate HNSW index.
This is especially useful to compare exact and approximate results in order to perform
tuning of HNSW parameters.
This annotation is default true when an HNSW index is specified,
otherwise it is always false. Setting this to false
might trigger graceful query degradation. Adjust
timeout as needed.
Tune how many extra nodes in the HNSW graph (in addition to totalTargetHits)
that should be explored before selecting the best hits. Default is 0. Increasing
this parameter increases the accuracy of the approximate search, at the cost of more distance computations.
Use to mark the query operator with a label
that can be referred to from the ranking expression in the rank profile.
See the closeness and
distance rank features.
Useful when having multiple nearestNeighbor operators in the same query,
e.g., when the schema has multiple vector fields.
See
nearest neighbor search guide
for usage example.
Tensor attribute with one indexed dimension of size N or with one or more mapped dimensions and one indexed dimension of size N.
Query model
Tensor with one indexed dimension of size N.
Matching
Returns documents where the distance (according to the
distance metric used)
between the document tensor
and the query tensor is less than the greatest distance among the current top-k best hits.
This means that typically more than top-k documents are matched and
returned for ranking. This is similar to the behavior of
wand.
When an HNSW index is used,
the top-k best hits are calculated before regular matching happens,
taking the rest of the query filters into account.
Ranking
Calculates a closeness score that is defined as
1 / (1 + d), where d is the distance
between the document tensor and query tensor.
This score is available using
rawScore,
itemRawScore, or
closeness rank features.
The raw distance is available using the
distance rank feature.
nonEmpty takes as its only argument an arbitrary search expression.
It will then perform a set of checks on that expression.
If all the checks pass, the result is the same expression, otherwise the query will fail.
The checks are as follows:
No empty search term
No empty operators, like phrases without terms
No null markers (NullItem) from e.g. failed query parsing
Note how "foo" is empty in this case, which will force the query to fail.
If "foo" contained a searchable term, the query would not have failed.
predicate
predicate() specifies a predicate query -
see predicate fields.
It takes three arguments: the predicate field to search, a map of attributes, and a map of range attributes:
Due to a quirk in YQL-parsing, one cannot specify an empty map, use the number 0 instead.
wherepredicate(predicate_field,0,{"age":20L})
true
Matches all documents of any type. Care must be taken when using this since processing all documents as matches
is expensive. At minimum, consider restricting to only one schema where you know the corpus isn't too big,
see the model.restrict URL parameter.
false
Does not match any document at all. Not useful in itself, but could potentially be used as
a placeholder in the query tree.
order by
Sort using order by.
Add asc or desc after the name of an
attribute to set sort order -
ascending order is default. Add another sorting attributes to get a secondary sort, that will be a tiebreaker for the
primary ordering attribute. This is typically used to get a predictable ordering when the primary ordering attribute
has the same value for multiple documents.
Sorting function, locale and strength are defined using the annotations "function", "locale" and "strength", as in:
wheretitlecontains"madonna"order by {function: "uca", locale: "en_US", strength: "IDENTICAL"}otherdesc, {function: "lowercase"}something
Note:match-phase
can be enabled automatically when sorting on attributes - refer to the sorting reference.
This optimization is not activated when the primary sort key is feature(...).
To sort by a rank feature or rank-profile function, use function: "feature" on its name:
wheretitlecontains"madonna"order by {function: "feature"}title_bm25desc, priceasc
The name must be listed in sort-features
in the selected rank profile. See sorting by rank feature
for the rank-profile definition and restrictions.
The rank profile determines the rank score each document will get.
Results are ordered by that value by default, but order by overrides that ordering.
Use the built-in rank-profile unranked for queries that sort only by attributes.
Feature sorting keeps the selected profile, but does not itself activate first- or second-phase ranking.
Include '[relevance]' (or '[rank]') to compute relevance scores and use them in sorting.
To do a primary ordering on the rank score, and a secondary sort on an attribute, use '[relevance]' as the first order by attribute.
See Special sorting attributes for more details.
To specify a slice / limit the number of hits returned / do pagination,
use limit and/or offset. This can also be controlled by using
native execution parameters.
Important:
Values set in YQL takes precedence over
hits/offset.
Values for hits/offset in query profiles are also overridden by YQL,
e.g., limit 100 overrides <field name="hits" overridable="false">50</field>.
Example: This returns two hits (if there are sufficiently many hits matching the query),
skipping the 29 first documents
wheretitlecontains"madonna"limit31offset29
timeout
Set query timeout in milliseconds using timeout. This can also be controlled by using the native
execution parameter timeout. YQL specified values takes precedence.:
wheretitlecontains"madonna"timeout70
Only literal numbers are valid, i.e. setting another unit is not supported.
Note:
The value is in milliseconds,
whereas the native execution parameter timeout is in seconds
Parameter substitution
Use parameter substitution to separate the YQL string from user input values.
E.g., the text(value) query operator
supports parameter substitution for the value parameter:
Note that the annotation is enclosed by parentheses to scope the annotation to the operator.
All annotations are supported by the string arguments to functions like
and phrase() and near() and also the string argument to the "contains" operator.
Some annotations are also supported by the functions which are handled like leaf nodes internally in the query tree:
phrase(), near(), onear(), range(), equiv(), dotProduct(), weightedSet(), weakAnd(), wand() and nearestNeighbor().
Remove accents from this term if it is the setting for this field.
Refer to linguistics.
allowEmpty
false
boolean
Whether to allow empty input for query parsing and query terms in text/userInput.
If true, a NullItem instance is inserted in the proper place in the query tree.
If false, the query will fail if the user provided input can not be parsed or is empty.
andSegmenting
true|false
Force phrase or AND operator if re-segmenting (e.g. in stemming) this term results in multiple terms.
Default is choosing from language settings.
annotations
map
Map of string: string. Custom annotations. No special semantics inside the YQL layer. Example:
annotations : {cox: "another"}
approximate
boolean
Used in nearestNeighbor.
The optional approximate annotation may be set to false to disallow usage of an approximate
HNSW index.
This is especially useful to compare exact and approximate results in order to perform tuning of other parameters.
This annotation is default true when an HNSW index is specified,
otherwise it is always false.
A numeric interval is by default a closed interval.
If the lower bound is exclusive, set to leftOpen.
If the upper bound is exclusive, set to rightOpen.
If both bounds are exclusive, set the annotation to open.
Example:
where ({bounds:"rightOpen"}range(year, 2000, 2018))
connectivity
map
Map of id: int, weight: double of explicit connectivity between this item
and the item with the given id -
see text matching and ranking.
Example:
The distance annotation sets the maximum position difference to count as a match,
see near / onear.
All matching terms must fit within positions [P, P+distance] where P is the first term's position.
Default is 2.
wheretextcontains ({distance: 5}near("a", "b"))
elementFilter
list of int
Used with sameElement.
Restricts matching in an array field to specific indices.
A non-empty list makes sameElement match
if and only if there is a match at one or more of the specified indices.
Used in nearestNeighbor.
The distanceThreshold annotation may be used to filter away hits
with a higher distance than the given threshold from the results.
Note that one will never get more hits with distanceThreshold than you would get without it -
to get more hits, increase totalTargetHits, too.
The units for the threshold depends on the
distance metric used.
endAnchor
true
boolean
Deprecated:
the uri type is deprecated.
The hostname subfield of uri
supports anchoring to the start and/or end of the hostname,
controlled by the startAnchor and endAnchor annotations.
Anchoring to the end is on by default while anchoring to the start is not. Hence
Regard this term as a "filter" term and not a term from the end user.
Terms that are annotated with "filter:true" are not bolded.
See also model.filter. Bolding of terms
is controlled by schema:bolding.
function
Default sort function for strings is uca.
Field sort specification can be configured in the schema,
values in the query overrides the schema settings.
Numeric fields are numerically sorted.
Function
Description
feature
Sorts numerically by a scalar rank feature or rank-profile function without arguments,
listed in the selected profile's sort-features.
The annotated name is the feature name, for example {function: "feature"}title_bm25 desc.
The default order is ascending.
See sorting by rank feature.
Both locale and strength are optional,
however strength requires locale.
The locale query annotation will override
locale-setting in the schema.
If locale is missing from both, the lowercase function will be used by default.
lowercase
This improves the sorting by first lowercasing and normalising the strings before sorting.
This is slightly more correct and might be enough for the use case.
It is not that much more costly than raw sort, and less expensive than uca.
raw
Raw byteorder is a simple and fast ordering based on memcmp of utf8 for strings
and correct sort order compliant binary rep for other fields is done.
However, that is not correct for anything except computers,
looking only at the binary representation.
grammar
weakAnd
raw, segment and all values accepted for the
model.type argument in the query API.
How to parse userInput.
raw will treat the user input as a string to be matched without any processing,
segment will do a first pass through the linguistic libraries,
while the rest of the values will treat the string as a query to be parsed.
The individual model.type settings can also be set, using
grammar.composite, grammar.tokenization, grammar.syntax, and
grammar.profile—refer to the model.type documentation.
Numeric operations support hitLimit.
This is used for capped range search.
An alternative to using negative and positive values for hitLimit is always using a positive number of hits
(as a negative number of hits does not make much sense) and combine this with either of the
ascending and descending annotations (but not both).
Example: {hitLimit: 38, descending: true} would be equivalent to setting it to -38,
i.e. only populate with 38 hits and start from upper boundary, i.e. descending order.
Note that hitLimit will limit the number of documents that are considered.
This is a powerful optimisation that must be used with care,
particularly in combination with other filters.
The set of documents to be considered will be limited upfront
by only selecting the N best according to the range query and the hitLimit annotation,
for further query evaluation.
hitLimit is not exact, but "at least".
In addition, it will only kick in if the attribute has fast-search.
It will look up the upper or lower bound in the range in the dictionary and scan in ascending or descending order
and select entries until it has satisfied hitLimit.
You will get all documents for all the dictionary entries selected.
Used in nearestNeighbor.
When using an HNSW index,
the optional hnsw.exploreAdditionalHits annotation can be used to
tune how many extra nodes in the graph (in addition to totalTargetHits)
should be explored before selecting the best hits.
Using a greater number here gives better quality, but worse performance.
Implicit term transformations (field defaults).
If implicitTransforms is true,
the settings for the field in the schema will be honored in term transforms,
e.g. if the field has stemming, this term will be stemmed.
If implicitTransforms is false,
the search backend will receive the term exactly as written in the initial YQL expression.
This is in other words a top level switch to turn off all other
stemming, accent removal, Unicode
normalizations and so on.
label
string
Attaches a symbolic name to this query item so that it can be referred to from ranking,
see
query item labeling.
The label is carried by single terms, or operators like and, or or
nearestNeighbor. Sub-clauses inherit the label of their parent, but
can override it.
Stem this term if it is the setting for this field.
strength
PRIMARY
PRIMARY
SECONDARY
TERTIARY
QUATERNARY
IDENTICAL
Used by the UCA sort function.
Default is PRIMARY, which only sorts on primary differentiating characteristics;
this means that letters in uppercase/lowercase or with differences in accents only are considered equal.
suffix
false
boolean
Do suffix matching for this term, e.g. search for "*word".
totalTargetHits
100
int
Used with wand and weakAnd, where the default is 100,
and with nearestNeighbor, where it has no default.
This sets the wanted number of hits exposed to the first-phase ranking function in total
over the content nodes evaluating the query (a group).
If additional second phase ranking is used,
do not set totalTargetHits less than the configured rank-profile's
total-rerank-count.
Used with nearestNeighbor.
Specifies the minimum target hits to produce in this nearest neighbor operator.
The default value is 100. Exploring too little in a graph leads to bad quality,
and this parameter protects against that when totalTargetHits leads to some node with
little content otherwise getting a low targetHits.
Each content node resolves its per-node target hits as
max(minTargetHits, ceil(totalTargetHits × share)), where share
is the node's share of the active documents in the
group serving the query - not across
the whole cluster, since a query is dispatched to a single group. A node that has just joined
the cluster, or is still receiving documents after a topology change, temporarily holds little
content and would get too few hits from totalTargetHits alone without this floor.
Note:
Setting minTargetHits higher than a node's expected share of
totalTargetHits makes minTargetHits the effective value, and totalTargetHits has no further
effect until it exceeds the floor. This is easy to hit when moving from a flat to a grouped
topology, since a group typically has fewer nodes than the full cluster.
targetHits
100
int
Sets target hits per node. Prefer using totalTargetHits over this.
usePositionData
true
boolean
Use term position data for text ranking features such as nativeRank.
This is term position, not to be confused with
geo searches. Setting "usePositionData:false" can improve query performance.
The "stem" annotation controls whether a given term should be stemmed if its
field is configured as a stemmed field (default is "true").
The "AND" operator itself has no internal API for whether its operands should be stemmed or not,
but we can still annotate as such,
because when the value of a given annotation is determined,
the expression tree is followed from the term in question and up through its ancestors.
Traversing the tree stops when a value is found (or there is nothing more to traverse).
In other words, none of the terms in this example will be stemmed.
How annotations behave may be easier to understand of expressing a boolean query in the style of an S-expression:
The annotation scopes would then be as follows, i.e. annotations on
which elements will be checked when determining the settings for a given term:
term1
term1 itself, and the first AND
term2
term2 itself, and the first AND
term3
term3 itself, the first OR and the first AND
term4
term4 itself, the first OR and the first AND
term5
term5 itself, the second OR and the first AND
term6
term6 itself, the second AND, the second OR and the first AND
term7
term7 itself, the second AND, the second OR and the first AND
Query properties
Use YQL variable syntax to initialize words in phrases and as single terms.
This removes the need for caring about quoting a term in YQL, as well as URL quoting.
The term will be used exactly as it is in the URL.
As an example, look at a query with a YQL argument, and the properties
animal and syntaxExample:
YQL requires quoting to be included in a URL.
Since YQL is well suited to application logic, while not being intended for end users,
a solution to this is storing the application's YQL queries into different
query profiles.
To add a default query profile, add search/query-profiles/default.xml to the
application package:
<query-profileid="default"><fieldname="yql">select * from sources * where default contains "latest" or userQuery()</field></query-profile>
This will add latest as an OR term to all queries not having an explicit query profile parameter.
The important thing to note is how it is not necessary to URL-quote anything in the query profiles files.
They operate independently of the HTTP parsing as such.
Query rewriting in Searchers
Searchers which modifies the textual YQL statement (not recommended)
should be annotated with @Before("ExternalYql").
Searchers modifying query tree produced from an input YQL statement
should annotate with @After("ExternalYql").
Grouping
Group / aggregate results by adding a grouping expression after a | -
read more.