Full text operators

The query string can contain certain operators that allow telling the conditions of how the words from the query string should be matched.

Boolean operators

AND operator

There always is implicit AND operator, so “hello world” means that both “hello” and “world” must be present in matching document.

  1. hello world

OR operator

OR operator precedence is higher than AND, so looking for cat | dog | mouse means looking for ( cat | dog | mouse ) and not (looking for cat) | dog | mouse.

  1. hello | world

MAYBE operator

  1. hello MAYBE world

MAYBE operator works much like operator | but doesn’t return documents which match only right subtree expression.

Negation operator

  1. hello -world
  2. hello !world

The negation operator enforces a rule for a word to not exist.

Queries having only negations are not supported by default in Manticore Search. There’s the server option not_terms_only_allowed to enable it.

Field search operator

  1. @title hello @body world

Field limit operator limits subsequent searching to a given field. Normally, query will fail with an error message if given field name does not exist in the searched table. However, that can be suppressed by specifying @@relaxed option at the very beginning of the query:

  1. @@relaxed @nosuchfield my query

This can be helpful when searching through heterogeneous tables with different schemas.

Field position limit additionally restricts the searching to first N position within given field (or fields). For example, @body [50] hello will not match the documents where the keyword hello occurs at position 51 and below in the body.

  1. @body[50] hello

Multiple-field search operator:

  1. @(title,body) hello world

Ignore field search operator (will ignore any matches of ‘hello world’ from field ‘title’):

  1. @!title hello world

Ignore multiple-field search operator (if we have fields title, subject and body then @!(title) is equivalent to @(subject,body)):

  1. @!(title,body) hello world

All-field search operator:

  1. @* hello

Phrase search operator

  1. "hello world"

The phrase operator requires the words to be next to each other.

The phrase search operator may include a match any term modifier. Terms within the phrase operator are position significant. When the ‘match any term’ modifier is implemented, the position of the subsequent terms from that phrase query will be shifted. Therefore, ‘match any’ has no impact on search performance.

  1. "exact * phrase * * for terms"

Proximity search operator

  1. "hello world"~10

Proximity distance is specified in words, adjusted for word count, and applies to all words within quotes. For instance, "cat dog mouse"~5 query means that there must be less than 8-word span which contains all 3 words, ie. CAT aaa bbb ccc DOG eee fff MOUSE document will not match this query, because this span is exactly 8 words long.

Quorum matching operator

  1. "the world is a wonderful place"/3

Quorum matching operator introduces a kind of fuzzy matching. It will only match those documents that pass a given threshold of given words. The example above ("the world is a wonderful place"/3) will match all documents that have at least 3 of the 6 specified words. Operator is limited to 255 keywords. Instead of an absolute number, you can also specify a number between 0.0 and 1.0 (standing for 0% and 100%), and Manticore will match only documents with at least the specified percentage of given words. The same example above could also have been written "the world is a wonderful place"/0.5 and it would match documents with at least 50% of the 6 words.

Strict order operator

  1. aaa << bbb << ccc

Strict order operator (aka operator “before”) will match the document only if its argument keywords occur in the document exactly in the query order. For instance, black << cat query (without quotes) will match the document “black and white cat” but not the “that cat was black” document. Order operator has the lowest priority. It can be applied both to just keywords and more complex expressions, ie. this is a valid query:

  1. (bag of words) << "exact phrase" << red|green|blue

Exact form modifier

  1. raining =cats and =dogs
  2. ="exact phrase"

Exact form keyword modifier will match the document only if the keyword occurred in exactly the specified form. The default behaviour is to match the document if the stemmed/lemmatized keyword matches. For instance, “runs” query will match both the document that contains “runs” and the document that contains “running”, because both forms stem to just “run” while =runs query will only match the first document. Exact form operator requires index_exact_words option to be enabled.

Another use case is to avoid expanding a keyword to its *keyword* form. I.e. with index_exact_words=1 + expand_keywords=1/star bcd will find a document containing abcde, but =bcd will not.

This is a modifier that affects the keyword and thus can be used within operators such as phrase, proximity, and quorum operators. It is possible to apply an exact form modifier to the phrase operator. In this case it internally adds the exact form modifier to all terms in the phrase.

Wildcard operators

  1. nation* *nation* *national

Requires min_infix_len for prefix (expansion in trail) and/or sufix (expansion in head). If only prefixing is wanted, min_prefix_len can be used instead.

The search will try to find all the expansions of the wildcarded tokens and each expansion is recorded as a matched hit. The number of expansions for a token can be controlled with expansion_limit table setting. Wildcarded tokens can have a big impact on the query search time, especially when tokens have short length. In such cases is desired to use the expansion limit.

The wildcard operator can be automatically applied if expand_keywords table setting is used.

In addition, the following inline wildcard operators are supported:

  • ? can match any(one) character: t?st will match test, but not teast
  • % can match zero or one character : tes% will match tes or test, but not testing

The inline operators require dict=keywords and infixing enabled.

Field-start and field-end modifier

  1. ^hello world$

Field-start and field-end keyword modifiers will make the keyword match only if it occurred at the very start or the very end of a fulltext field, respectively. For instance, the query "^hello world$" (with quotes and thus combining phrase operator and start/end modifiers) will only match documents that contain at least one field that has exactly these two keywords.

IDF boost modifier

  1. boosted^1.234 boostedfieldend$^1.234

The boost modifier increases the word IDF score by the specified factor in ranking scores that use IDF in their formula. It does not affect the matching in any way.

NEAR operator

  1. hello NEAR/3 world NEAR/4 "my test"

Operator NEAR is a generalized version of the proximity operator. The syntax is NEAR/N, it is case-sensitive, and no spaces are allowed between the NEAR keywords, the slash sign, and the distance value.

The original proximity operator only works on sets of keywords. NEAR is more generic and can accept arbitrary subexpressions as its two arguments, matching the document when both subexpressions are found within N words of each other, no matter in which order. NEAR is left associative and has the same (lowest) precedence as BEFORE.

You should also note how one NEAR/7 two NEAR/7 three is not really equivalent to "one two three"~7. The difference here is that the proximity operator allows for up to 6 non-matching words between all the 3 matching words, but the version with NEAR is less restrictive: it would allow for up to 6 words between one and two and then for up to 6 more between that two-word matching and three.

NOTNEAR operator

  1. Church NOTNEAR/3 street

Operator NOTNEAR is a negative assertion. It matches the document when left argument exists and either there is no right argument in document or right argument is distance away from left matched argument’s end. The distance is specified in words. The syntax is NOTNEAR/N, it is case-sensitive, and no spaces are allowed between the NOTNEAR keyword, the slash sign, and the distance value. Both arguments of this operator might be terms or any operators or group of operators.

SENTENCE and PARAGRAPH operators

  1. all SENTENCE words SENTENCE "in one sentence"
  1. "Bill Gates" PARAGRAPH "Steve Jobs"

SENTENCE and PARAGRAPH operators matches the document when both its arguments are within the same sentence or the same paragraph of text, respectively. The arguments can be either keywords, or phrases, or the instances of the same operator.

The order of the arguments within the sentence or paragraph does not matter. These operators only work on tables built with index_sp (sentence and paragraph indexing feature) enabled, and revert to a mere AND otherwise. Refer to the index_sp directive documentation for the notes on what’s considered a sentence and a paragraph.

ZONE limit operator

  1. ZONE:(h3,h4)
  2. only in these titles

ZONE limit operator is quite similar to field limit operator, but restricts matching to a given in-field zone or a list of zones. Note that the subsequent subexpressions are not required to match in a single contiguous span of a given zone, and may match in multiple spans. For instance, (ZONE:th hello world) query will match this example document:

  1. <th>Table 1. Local awareness of Hello Kitty brand.</th>
  2. .. some table data goes here ..
  3. <th>Table 2. World-wide brand awareness.</th>

ZONE operator affects the query until the next field or ZONE limit operator, or the closing parenthesis. It only works on the tables built with zones support (see index_zones) and will be ignored otherwise.

ZONESPAN limit operator

  1. ZONESPAN:(h2)
  2. only in a (single) title

ZONESPAN limit operator is similar to the ZONE operator, but requires the match to occur in a single contiguous span. In the example above, ZONESPAN:th hello world would not match the document, since “hello” and “world” do not occur within the same span.

Escaping characters in query string

As some characters are used as operators in the query string, they should be escaped to avoid query errors or unwanted matching conditions.

The following characters should be escaped using backslash (\):

  1. ! " $ ' ( ) - / < @ \ ^ | ~

In MySQL command line client

Single quote (‘) can be escaped using one backslash:

  1. SELECT * FROM your_index WHERE MATCH('l\'italiano');

The rest of the characters in the above list are operators or query constructs. In order to treat them as simple characters, the engine has to see them with a preceding escape character. The backslash must also be escaped itself, resulting in 2 backslahes:

  1. SELECT * FROM your_index WHERE MATCH('r\\&b | \\(official video\\)');

If we want to use backslash as character, we need to escape both the backslash as character and backslash as the escape operator, resulting in 4 backslashes used:

  1. SELECT * FROM your_index WHERE MATCH('\\\\ABC');

Using MySQL drivers

MySQL drivers offer escaping functions (e.g., mysqli_real_escape_string in PHP or conn.escape_string in Python), but they only escape certain characters. You will still need to add escaping for the characters from the above list that are not escaped by the respective functions. Since these functions will escape backslash for you, you only need to add one backslash.

This also applies for the drivers that support (client-side) prepared statements. For example for PHP PDO prepared statements, you need to add a backslash for $ character:

  1. $statement = $ln_sph->prepare( "SELECT * FROM index WHERE MATCH(:match)");
  2. $match = '\$manticore';
  3. $statement->bindParam(':match',$match,PDO::PARAM_STR);
  4. $results = $statement->execute();

It will make the final query SELECT * FROM index WHERE MATCH('\\$manticore');

In HTTP JSON API

The same rules for SQL protocol apply with the exception that for JSON the double quote must be escaped with a single backslash, while the rest of the characters must be double escaped.

If using JSON libraries/functions that convert data structures to JSON strings the double quote and single backslash are escaped automatically by these functions and must not be explicitly escaped.

In clients

The new official clients (which use HTTP as protocol) are using under the hood common JSON libraries/functions available on the respective programming language. Same rules of escaping as above are applied.

Escaping asterisk

Asterisk (*) is a special character that can have two functionalities:

  • as wildcarding prefix/suffix expander
  • and as any term modifier inside a phrase search.

Unlike other special characters that are operators, the asterisk cannot be escaped when it’s in a position to offer one of it’s functionalities.

In non-wildcard queries, the asterisk doesn’t require escaping, regardless if it’s in the charset_table or not.

In wildcard queries, asterisk in the middle of a word doesn’t require escaping. As a wildcard operator (either at start or end of the word), the asterisk will always be interpreted as the wildcard operator even if escaping is applied.

Escaping json node names in SQL

To escape special characters in json nodes use a backtick. For example:

  1. MySQL [(none)]> select * from t where json.`a=b`=234;
  2. +---------------------+-------------+------+
  3. | id | json | text |
  4. +---------------------+-------------+------+
  5. | 8215557549554925578 | {"a=b":234} | |
  6. +---------------------+-------------+------+
  7. MySQL [(none)]> select * from t where json.`a:b`=123;
  8. +---------------------+-------------+------+
  9. | id | json | text |
  10. +---------------------+-------------+------+
  11. | 8215557549554925577 | {"a:b":123} | |
  12. +---------------------+-------------+------+

Search profiling

How a query is interpreted

Example of a complex query:

  1. "hello world" @title "example program"~5 @body python -(php|perl) @* code

The full meaning of this search is:

  • Find the words ‘hello’ and ‘world’ adjacently in any field in a document;
  • Additionally, the same document must also contain the words ‘example’ and ‘program’ in the title field, with up to, but not including, 5 words between the words in question; (E.g. “example PHP program” would be matched however “example script to introduce outside data into the correct context for your program” would not because two terms have 5 or more words between them)
  • Additionally, the same document must contain the word ‘python’ in the body field, but not contain either ‘php’ or ‘perl’;
  • Additionally, the same document must contain the word ‘code’ in any field.

OR operator precedence is higher than AND, so “looking for cat | dog | mouse” means “looking for ( cat | dog | mouse )” and not “(looking for cat) | dog | mouse”.

To understand how a query will be executed, Manticore Search offer query profile tooling for viewing the query tree created by a query expression.

Profiling the query tree in SQL

When using SQL statement the full-text query profiling needs to be enabled before running the desired query:

  1. SET profiling =1;
  2. SELECT * FROM test WHERE MATCH('@title abc* @body hey');

To view the query tree, we must run SHOW PLAN right after the execution of the query:

  1. SHOW PLAN;

The command will return the structure of the executed query. Please note that the 3 statements - SET profiling, the query and SHOW - must run on the same session.

Profiling the query in HTTP JSON

When using the HTTP JSON protocol we can just enable "profile":true to get in response the full-text query tree structure.

  1. {
  2. "index":"test",
  3. "profile":true,
  4. "query":
  5. {
  6. "match_phrase": { "_all" : "had grown quite" }
  7. }
  8. }

The response will contain a profile object in which we can find a member query.

query property contains the transformed full-text query tree. Each node contains:

  • type: node type. Can be AND, OR, PHRASE, KEYWORD etc.
  • description: query subtree for this node shown as a string (in SHOW PLAN format)
  • children: child nodes, if any
  • max_field_pos: maximum position within a field

A keyword node will also provide:

  • word: transformed keyword.
  • querypos: position of this keyword in a query.
  • excluded: keyword excluded from query.
  • expanded: keyword added by prefix expansion.
  • field_start: keyword must occur at the very start of the field.
  • field_end: keyword must occur at the very end of the field.
  • boost: keyword IDF will be multiplied by this.
  • SQL
  • JSON
  • PHP
  • Python
  • javascript
  • Java

SQL JSON PHP Python javascript Java

  1. SET profiling=1;
  2. SELECT * FROM test WHERE MATCH('@title abc* @body hey');
  3. SHOW PLAN \G
  1. POST /search
  2. {
  3. "index": "forum",
  4. "query": {"query_string": "i me"},
  5. "_source": { "excludes":["*"] },
  6. "limit": 1,
  7. "profile":true
  8. }
  1. $result = $index->search('i me')->setSource(['excludes'=>['*']])->setLimit(1)->profile()->get();
  2. print_r($result->getProfile());
  1. searchApi.search({"index":"forum","query":{"query_string":"i me"},"_source":{"excludes":["*"]},"limit":1,"profile":True})
  1. res = await searchApi.search({"index":"forum","query":{"query_string":"i me"},"_source":{"excludes":["*"]},"limit":1,"profile":true});
  1. query = new HashMap<String,Object>();
  2. query.put("query_string","i me");
  3. searchRequest = new SearchRequest();
  4. searchRequest.setIndex("forum");
  5. searchRequest.setQuery(query);
  6. searchRequest.setProfile(true);
  7. searchRequest.setLimit(1);
  8. searchRequest.setSort(new ArrayList<String>(){{
  9. add("*");
  10. }});
  11. searchResponse = searchApi.search(searchRequest);

Response

  1. *************************** 1\. row ***************************
  2. Variable: transformed_tree
  3. Value: AND(
  4. OR(fields=(title), KEYWORD(abcx, querypos=1, expanded), KEYWORD(abcm, querypos=1, expanded)),
  5. AND(fields=(body), KEYWORD(hey, querypos=2)))
  6. 1 row in set (0.00 sec)
  1. {
  2. "took":1503,
  3. "timed_out":false,
  4. "hits":
  5. {
  6. "total":406301,
  7. "hits":
  8. [
  9. {
  10. "_id":"406443",
  11. "_score":3493,
  12. "_source":{}
  13. }
  14. ]
  15. },
  16. "profile":
  17. {
  18. "query":
  19. {
  20. "type":"AND",
  21. "description":"AND( AND(KEYWORD(i, querypos=1)), AND(KEYWORD(me, querypos=2)))",
  22. "children":
  23. [
  24. {
  25. "type":"AND",
  26. "description":"AND(KEYWORD(i, querypos=1))",
  27. "children":
  28. [
  29. {
  30. "type":"KEYWORD",
  31. "word":"i",
  32. "querypos":1
  33. }
  34. ]
  35. },
  36. {
  37. "type":"AND",
  38. "description":"AND(KEYWORD(me, querypos=2))",
  39. "children":
  40. [
  41. {
  42. "type":"KEYWORD",
  43. "word":"me",
  44. "querypos":2
  45. }
  46. ]
  47. }
  48. ]
  49. }
  50. }
  51. }
  1. Array
  2. (
  3. [query] => Array
  4. (
  5. [type] => AND
  6. [description] => AND( AND(KEYWORD(i, querypos=1)), AND(KEYWORD(me, querypos=2)))
  7. [children] => Array
  8. (
  9. [0] => Array
  10. (
  11. [type] => AND
  12. [description] => AND(KEYWORD(i, querypos=1))
  13. [children] => Array
  14. (
  15. [0] => Array
  16. (
  17. [type] => KEYWORD
  18. [word] => i
  19. [querypos] => 1
  20. )
  21. )
  22. )
  23. [1] => Array
  24. (
  25. [type] => AND
  26. [description] => AND(KEYWORD(me, querypos=2))
  27. [children] => Array
  28. (
  29. [0] => Array
  30. (
  31. [type] => KEYWORD
  32. [word] => me
  33. [querypos] => 2
  34. )
  35. )
  36. )
  37. )
  38. )
  39. )
  1. {'hits': {'hits': [{u'_id': u'100', u'_score': 2500, u'_source': {}}],
  2. 'total': 1},
  3. 'profile': {u'query': {u'children': [{u'children': [{u'querypos': 1,
  4. u'type': u'KEYWORD',
  5. u'word': u'i'}],
  6. u'description': u'AND(KEYWORD(i, querypos=1))',
  7. u'type': u'AND'},
  8. {u'children': [{u'querypos': 2,
  9. u'type': u'KEYWORD',
  10. u'word': u'me'}],
  11. u'description': u'AND(KEYWORD(me, querypos=2))',
  12. u'type': u'AND'}],
  13. u'description': u'AND( AND(KEYWORD(i, querypos=1)), AND(KEYWORD(me, querypos=2)))',
  14. u'type': u'AND'}},
  15. 'timed_out': False,
  16. 'took': 0}
  1. {"hits": {"hits": [{"_id": "100", "_score": 2500, "_source": {}}],
  2. "total": 1},
  3. "profile": {"query": {"children": [{"children": [{"querypos": 1,
  4. "type": "KEYWORD",
  5. "word": "i"}],
  6. "description": "AND(KEYWORD(i, querypos=1))",
  7. "type": "AND"},
  8. {"children": [{"querypos": 2,
  9. "type": "KEYWORD",
  10. "word": "me"}],
  11. "description": "AND(KEYWORD(me, querypos=2))",
  12. "type": "AND"}],
  13. "description": "AND( AND(KEYWORD(i, querypos=1)), AND(KEYWORD(me, querypos=2)))",
  14. "type": "AND"}},
  15. "timed_out": False,
  16. "took": 0}
  1. class SearchResponse {
  2. took: 18
  3. timedOut: false
  4. hits: class SearchResponseHits {
  5. total: 1
  6. hits: [{_id=100, _score=2500, _source={}}]
  7. aggregations: null
  8. }
  9. profile: {query={type=AND, description=AND( AND(KEYWORD(i, querypos=1)), AND(KEYWORD(me, querypos=2))), children=[{type=AND, description=AND(KEYWORD(i, querypos=1)), children=[{type=KEYWORD, word=i, querypos=1}]}, {type=AND, description=AND(KEYWORD(me, querypos=2)), children=[{type=KEYWORD, word=me, querypos=2}]}]}}
  10. }

In some cases the evaluated query tree can be rather different from the original one because of expansions and other transformations.

  • SQL
  • JSON
  • PHP
  • Python
  • javascript
  • Java

SQL JSON PHP Python javascript Java

  1. SET profiling=1;
  2. SELECT id FROM forum WHERE MATCH('@title way* @content hey') LIMIT 1;
  3. SHOW PLAN;
  1. POST /search
  2. {
  3. "index": "forum",
  4. "query": {"query_string": "@title way* @content hey"},
  5. "_source": { "excludes":["*"] },
  6. "limit": 1,
  7. "profile":true
  8. }
  1. $result = $index->search('@title way* @content hey')->setSource(['excludes'=>['*']])->setLimit(1)->profile()->get();
  2. print_r($result->getProfile());
  1. searchApi.search({"index":"forum","query":{"query_string":"@title way* @content hey"},"_source":{"excludes":["*"]},"limit":1,"profile":true})
  1. res = await searchApi.search({"index":"forum","query":{"query_string":"@title way* @content hey"},"_source":{"excludes":["*"]},"limit":1,"profile":true});
  1. query = new HashMap<String,Object>();
  2. query.put("query_string","@title way* @content hey");
  3. searchRequest = new SearchRequest();
  4. searchRequest.setIndex("forum");
  5. searchRequest.setQuery(query);
  6. searchRequest.setProfile(true);
  7. searchRequest.setLimit(1);
  8. searchRequest.setSort(new ArrayList<String>(){{
  9. add("*");
  10. }});
  11. searchResponse = searchApi.search(searchRequest);

Response

  1. Query OK, 0 rows affected (0.00 sec)
  2. +--------+
  3. | id |
  4. +--------+
  5. | 711651 |
  6. +--------+
  7. 1 row in set (0.04 sec)
  8. +------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  9. | Variable | Value |
  10. +------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  11. | transformed_tree | AND(
  12. OR(
  13. OR(
  14. AND(fields=(title), KEYWORD(wayne, querypos=1, expanded)),
  15. OR(
  16. AND(fields=(title), KEYWORD(ways, querypos=1, expanded)),
  17. AND(fields=(title), KEYWORD(wayyy, querypos=1, expanded)))),
  18. AND(fields=(title), KEYWORD(way, querypos=1, expanded)),
  19. OR(fields=(title), KEYWORD(way*, querypos=1, expanded))),
  20. AND(fields=(content), KEYWORD(hey, querypos=2))) |
  21. +------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  22. 1 row in set (0.00 sec)
  1. {
  2. "took":33,
  3. "timed_out":false,
  4. "hits":
  5. {
  6. "total":105,
  7. "hits":
  8. [
  9. {
  10. "_id":"711651",
  11. "_score":2539,
  12. "_source":{}
  13. }
  14. ]
  15. },
  16. "profile":
  17. {
  18. "query":
  19. {
  20. "type":"AND",
  21. "description":"AND( OR( OR( AND(fields=(title), KEYWORD(wayne, querypos=1, expanded)), OR( AND(fields=(title), KEYWORD(ways, querypos=1, expanded)), AND(fields=(title), KEYWORD(wayyy, querypos=1, expanded)))), AND(fields=(title), KEYWORD(way, querypos=1, expanded)), OR(fields=(title), KEYWORD(way*, querypos=1, expanded))), AND(fields=(content), KEYWORD(hey, querypos=2)))",
  22. "children":
  23. [
  24. {
  25. "type":"OR",
  26. "description":"OR( OR( AND(fields=(title), KEYWORD(wayne, querypos=1, expanded)), OR( AND(fields=(title), KEYWORD(ways, querypos=1, expanded)), AND(fields=(title), KEYWORD(wayyy, querypos=1, expanded)))), AND(fields=(title), KEYWORD(way, querypos=1, expanded)), OR(fields=(title), KEYWORD(way*, querypos=1, expanded)))",
  27. "children":
  28. [
  29. {
  30. "type":"OR",
  31. "description":"OR( AND(fields=(title), KEYWORD(wayne, querypos=1, expanded)), OR( AND(fields=(title), KEYWORD(ways, querypos=1, expanded)), AND(fields=(title), KEYWORD(wayyy, querypos=1, expanded))))",
  32. "children":
  33. [
  34. {
  35. "type":"AND",
  36. "description":"AND(fields=(title), KEYWORD(wayne, querypos=1, expanded))",
  37. "fields":["title"],
  38. "max_field_pos":0,
  39. "children":
  40. [
  41. {
  42. "type":"KEYWORD",
  43. "word":"wayne",
  44. "querypos":1,
  45. "expanded":true
  46. }
  47. ]
  48. },
  49. {
  50. "type":"OR",
  51. "description":"OR( AND(fields=(title), KEYWORD(ways, querypos=1, expanded)), AND(fields=(title), KEYWORD(wayyy, querypos=1, expanded)))",
  52. "children":
  53. [
  54. {
  55. "type":"AND",
  56. "description":"AND(fields=(title), KEYWORD(ways, querypos=1, expanded))",
  57. "fields":["title"],
  58. "max_field_pos":0,
  59. "children":
  60. [
  61. {
  62. "type":"KEYWORD",
  63. "word":"ways",
  64. "querypos":1,
  65. "expanded":true
  66. }
  67. ]
  68. },
  69. {
  70. "type":"AND",
  71. "description":"AND(fields=(title), KEYWORD(wayyy, querypos=1, expanded))",
  72. "fields":["title"],
  73. "max_field_pos":0,
  74. "children":
  75. [
  76. {
  77. "type":"KEYWORD",
  78. "word":"wayyy",
  79. "querypos":1,
  80. "expanded":true
  81. }
  82. ]
  83. }
  84. ]
  85. }
  86. ]
  87. },
  88. {
  89. "type":"AND",
  90. "description":"AND(fields=(title), KEYWORD(way, querypos=1, expanded))",
  91. "fields":["title"],
  92. "max_field_pos":0,
  93. "children":
  94. [
  95. {
  96. "type":"KEYWORD",
  97. "word":"way",
  98. "querypos":1,
  99. "expanded":true
  100. }
  101. ]
  102. },
  103. {
  104. "type":"OR",
  105. "description":"OR(fields=(title), KEYWORD(way*, querypos=1, expanded))",
  106. "fields":["title"],
  107. "max_field_pos":0,
  108. "children":
  109. [
  110. {
  111. "type":"KEYWORD",
  112. "word":"way*",
  113. "querypos":1,
  114. "expanded":true
  115. }
  116. ]
  117. }
  118. ]
  119. },
  120. {
  121. "type":"AND",
  122. "description":"AND(fields=(content), KEYWORD(hey, querypos=2))",
  123. "fields":["content"],
  124. "max_field_pos":0,
  125. "children":
  126. [
  127. {
  128. "type":"KEYWORD",
  129. "word":"hey",
  130. "querypos":2
  131. }
  132. ]
  133. }
  134. ]
  135. }
  136. }
  137. }
  1. Array
  2. (
  3. [query] => Array
  4. (
  5. [type] => AND
  6. [description] => AND( OR( OR( AND(fields=(title), KEYWORD(wayne, querypos=1, expanded)), OR( AND(fields=(title), KEYWORD(ways, querypos=1, expanded)), AND(fields=(title), KEYWORD(wayyy, querypos=1, expanded)))), AND(fields=(title), KEYWORD(way, querypos=1, expanded)), OR(fields=(title), KEYWORD(way*, querypos=1, expanded))), AND(fields=(content), KEYWORD(hey, querypos=2)))
  7. [children] => Array
  8. (
  9. [0] => Array
  10. (
  11. [type] => OR
  12. [description] => OR( OR( AND(fields=(title), KEYWORD(wayne, querypos=1, expanded)), OR( AND(fields=(title), KEYWORD(ways, querypos=1, expanded)), AND(fields=(title), KEYWORD(wayyy, querypos=1, expanded)))), AND(fields=(title), KEYWORD(way, querypos=1, expanded)), OR(fields=(title), KEYWORD(way*, querypos=1, expanded)))
  13. [children] => Array
  14. (
  15. [0] => Array
  16. (
  17. [type] => OR
  18. [description] => OR( AND(fields=(title), KEYWORD(wayne, querypos=1, expanded)), OR( AND(fields=(title), KEYWORD(ways, querypos=1, expanded)), AND(fields=(title), KEYWORD(wayyy, querypos=1, expanded))))
  19. [children] => Array
  20. (
  21. [0] => Array
  22. (
  23. [type] => AND
  24. [description] => AND(fields=(title), KEYWORD(wayne, querypos=1, expanded))
  25. [fields] => Array
  26. (
  27. [0] => title
  28. )
  29. [max_field_pos] => 0
  30. [children] => Array
  31. (
  32. [0] => Array
  33. (
  34. [type] => KEYWORD
  35. [word] => wayne
  36. [querypos] => 1
  37. [expanded] => 1
  38. )
  39. )
  40. )
  41. [1] => Array
  42. (
  43. [type] => OR
  44. [description] => OR( AND(fields=(title), KEYWORD(ways, querypos=1, expanded)), AND(fields=(title), KEYWORD(wayyy, querypos=1, expanded)))
  45. [children] => Array
  46. (
  47. [0] => Array
  48. (
  49. [type] => AND
  50. [description] => AND(fields=(title), KEYWORD(ways, querypos=1, expanded))
  51. [fields] => Array
  52. (
  53. [0] => title
  54. )
  55. [max_field_pos] => 0
  56. [children] => Array
  57. (
  58. [0] => Array
  59. (
  60. [type] => KEYWORD
  61. [word] => ways
  62. [querypos] => 1
  63. [expanded] => 1
  64. )
  65. )
  66. )
  67. [1] => Array
  68. (
  69. [type] => AND
  70. [description] => AND(fields=(title), KEYWORD(wayyy, querypos=1, expanded))
  71. [fields] => Array
  72. (
  73. [0] => title
  74. )
  75. [max_field_pos] => 0
  76. [children] => Array
  77. (
  78. [0] => Array
  79. (
  80. [type] => KEYWORD
  81. [word] => wayyy
  82. [querypos] => 1
  83. [expanded] => 1
  84. )
  85. )
  86. )
  87. )
  88. )
  89. )
  90. )
  91. [1] => Array
  92. (
  93. [type] => AND
  94. [description] => AND(fields=(title), KEYWORD(way, querypos=1, expanded))
  95. [fields] => Array
  96. (
  97. [0] => title
  98. )
  99. [max_field_pos] => 0
  100. [children] => Array
  101. (
  102. [0] => Array
  103. (
  104. [type] => KEYWORD
  105. [word] => way
  106. [querypos] => 1
  107. [expanded] => 1
  108. )
  109. )
  110. )
  111. [2] => Array
  112. (
  113. [type] => OR
  114. [description] => OR(fields=(title), KEYWORD(way*, querypos=1, expanded))
  115. [fields] => Array
  116. (
  117. [0] => title
  118. )
  119. [max_field_pos] => 0
  120. [children] => Array
  121. (
  122. [0] => Array
  123. (
  124. [type] => KEYWORD
  125. [word] => way*
  126. [querypos] => 1
  127. [expanded] => 1
  128. )
  129. )
  130. )
  131. )
  132. )
  133. [1] => Array
  134. (
  135. [type] => AND
  136. [description] => AND(fields=(content), KEYWORD(hey, querypos=2))
  137. [fields] => Array
  138. (
  139. [0] => content
  140. )
  141. [max_field_pos] => 0
  142. [children] => Array
  143. (
  144. [0] => Array
  145. (
  146. [type] => KEYWORD
  147. [word] => hey
  148. [querypos] => 2
  149. )
  150. )
  151. )
  152. )
  153. )
  154. )
  1. {'hits': {'hits': [{u'_id': u'2811025403043381551',
  2. u'_score': 2643,
  3. u'_source': {}}],
  4. 'total': 1},
  5. 'profile': {u'query': {u'children': [{u'children': [{u'expanded': True,
  6. u'querypos': 1,
  7. u'type': u'KEYWORD',
  8. u'word': u'way*'}],
  9. u'description': u'AND(fields=(title), KEYWORD(way*, querypos=1, expanded))',
  10. u'fields': [u'title'],
  11. u'type': u'AND'},
  12. {u'children': [{u'querypos': 2,
  13. u'type': u'KEYWORD',
  14. u'word': u'hey'}],
  15. u'description': u'AND(fields=(content), KEYWORD(hey, querypos=2))',
  16. u'fields': [u'content'],
  17. u'type': u'AND'}],
  18. u'description': u'AND( AND(fields=(title), KEYWORD(way*, querypos=1, expanded)), AND(fields=(content), KEYWORD(hey, querypos=2)))',
  19. u'type': u'AND'}},
  20. 'timed_out': False,
  21. 'took': 0}
  1. {"hits": {"hits": [{"_id": "2811025403043381551",
  2. "_score": 2643,
  3. "_source": {}}],
  4. "total": 1},
  5. "profile": {"query": {"children": [{"children": [{"expanded": True,
  6. "querypos": 1,
  7. "type": "KEYWORD",
  8. "word": "way*"}],
  9. "description": "AND(fields=(title), KEYWORD(way*, querypos=1, expanded))",
  10. "fields": ["title"],
  11. "type": "AND"},
  12. {"children": [{"querypos": 2,
  13. "type": "KEYWORD",
  14. "word": "hey"}],
  15. "description": "AND(fields=(content), KEYWORD(hey, querypos=2))",
  16. "fields": ["content"],
  17. "type": "AND"}],
  18. "description": "AND( AND(fields=(title), KEYWORD(way*, querypos=1, expanded)), AND(fields=(content), KEYWORD(hey, querypos=2)))",
  19. "type": "AND"}},
  20. "timed_out": False,
  21. "took": 0}
  1. class SearchResponse {
  2. took: 18
  3. timedOut: false
  4. hits: class SearchResponseHits {
  5. total: 1
  6. hits: [{_id=2811025403043381551, _score=2643, _source={}}]
  7. aggregations: null
  8. }
  9. profile: {query={type=AND, description=AND( AND(fields=(title), KEYWORD(way*, querypos=1, expanded)), AND(fields=(content), KEYWORD(hey, querypos=2))), children=[{type=AND, description=AND(fields=(title), KEYWORD(way*, querypos=1, expanded)), fields=[title], children=[{type=KEYWORD, word=way*, querypos=1, expanded=true}]}, {type=AND, description=AND(fields=(content), KEYWORD(hey, querypos=2)), fields=[content], children=[{type=KEYWORD, word=hey, querypos=2}]}]}}
  10. }

Profiling without running a query

The SQL statement EXPLAIN QUERY allows displaying the execution tree of a provided full-text query without running an actual search query on the table.

  • SQL

SQL

  1. EXPLAIN QUERY index_base '@title running @body dog'\G

Response

  1. EXPLAIN QUERY index_base '@title running @body dog'\G
  2. *************************** 1\. row ***************************
  3. Variable: transformed_tree
  4. Value: AND(
  5. OR(
  6. AND(fields=(title), KEYWORD(run, querypos=1, morphed)),
  7. AND(fields=(title), KEYWORD(running, querypos=1, morphed))))
  8. AND(fields=(body), KEYWORD(dog, querypos=2, morphed)))

EXPLAIN QUERY ... option format=dot allows displaying the execution tree of a provided full-text query in hierarchical format suitable for visualization by existing tools, for example https://dreampuf.github.io/GraphvizOnline :

EXPLAIN QUERY graphviz example

  • SQL

SQL

  1. EXPLAIN QUERY tbl 'i me' option format=dot\G

Response

  1. EXPLAIN QUERY tbl 'i me' option format=dot\G
  2. *************************** 1. row ***************************
  3. Variable: transformed_tree
  4. Value: digraph "transformed_tree"
  5. {
  6. 0 [shape=record,style=filled,bgcolor="lightgrey" label="AND"]
  7. 0 -> 1
  8. 1 [shape=record,style=filled,bgcolor="lightgrey" label="AND"]
  9. 1 -> 2
  10. 2 [shape=record label="i | { querypos=1 }"]
  11. 0 -> 3
  12. 3 [shape=record,style=filled,bgcolor="lightgrey" label="AND"]
  13. 3 -> 4
  14. 4 [shape=record label="me | { querypos=2 }"]
  15. }

Viewing the match factors values

When expression ranker is used, it is possible to expose the values of the calculated factors using PACKEDFACTORS()).

The function returns:

  • the values of document level factors (like bm25, field_mask, doc_word_count)
  • list with each field that returned a hit (like lcs, hit_count, word_count, sum_idf, min_hit_pos etc.)
  • list with each keyword from the query and their tf and idf values

The values can be used to understand why certain documents get scored lower or higher in a search or to improve the existing ranking expression.

  • SQL

SQL

  1. SELECT id, PACKEDFACTORS() FROM test1 WHERE MATCH('test one') OPTION ranker=expr('1')\G

Response

  1. id: 1
  2. packedfactors(): bm25=569, bm25a=0.617197, field_mask=2, doc_word_count=2,
  3. field1=(lcs=1, hit_count=2, word_count=2, tf_idf=0.152356,
  4. min_idf=-0.062982, max_idf=0.215338, sum_idf=0.152356, min_hit_pos=4,
  5. min_best_span_pos=4, exact_hit=0, max_window_hits=1, min_gaps=2,
  6. exact_order=1, lccs=1, wlccs=0.215338, atc=-0.003974),
  7. word0=(tf=1, idf=-0.062982),
  8. word1=(tf=1, idf=0.215338)
  9. 1 row in set (0.00 sec)