Transforming data with Analyzers

Analyzers allow you to transform data, for sophisticated text processing and searching, either standalone or in combination with Views

While AQL string functions allow for basic text manipulation, true text processing including tokenization, language-specific word stemming, case conversion and removal of diacritical marks (accents) from characters only become possible with Analyzers.

Analyzers parse input values and transform them into sets of sub-values, for example by breaking up text into words. If they are used in Views then the documents’ attribute values of the linked collections are used as input and additional metadata is produced internally. The data can then be used for searching and sorting to provide the most appropriate match for the specified conditions, similar to queries to web search engines.

Analyzers can be used on their own to tokenize and normalize strings in AQL queries with the TOKENS() function.

How Analyzers process values depends on their type and configuration. The configuration is comprised of type-specific properties and list of features. The features control the additional metadata to be generated to augment View indexes, to be able to rank results for instance.

Analyzers can be managed via an HTTP API and through a JavaScript module.

Value Handling

While most of the Analyzer functionality is geared towards text processing, there is no restriction to strings as input data type when using them through Views – your documents could have attributes of any data type after all.

Strings are processed according to the Analyzer, whereas other primitive data types (null, true, false, numbers) are added to the index unchanged.

The elements of arrays are unpacked, processed and indexed individually, regardless of the level of nesting. That is, strings are processed by the configured Analyzer(s) and other primitive values are indexed as-is.

Objects, including any nested objects, are indexed as sub-attributes. This applies to sub-objects as well as objects in arrays. Only primitive values are added to the index, arrays and objects can not be searched for.

Also see:

  • SEARCH operation on how to query indexed values such as numbers and nested values
  • ArangoSearch Views for details about how compound data types (arrays, objects) get indexed

Analyzer Names

Each Analyzer has a name for identification with the following naming conventions:

  • The name must only consist of the letters a to z (both in lower and upper case), the numbers 0 to 9, underscore (_) and dash (-) symbols. This also means that any non-ASCII names are not allowed.
  • It must always start with a letter.
  • The maximum allowed length of a name is 254 bytes.
  • Analyzer names are case-sensitive.

Custom Analyzers are stored per database, in a system collection _analyzers. The names get prefixed with the database name and two colons, e.g. myDB::customAnalyzer.This does not apply to the globally available built-in Analyzers, which are not stored in an _analyzers collection.

Custom Analyzers stored in the _system database can be referenced in queries against other databases by specifying the prefixed name, e.g. _system::customGlobalAnalyzer. Analyzers stored in databases other than _system can not be accessed from within another database however.

Analyzer Types

The currently implemented Analyzer types are:

  • identity: treat value as atom (no transformation)
  • delimiter: split into tokens at user-defined character
  • stem: apply stemming to the value as a whole
  • norm: apply normalization to the value as a whole
  • ngram: create n-grams from value with user-defined lengths
  • text: tokenize into words, optionally with stemming, normalization, stop-word filtering and edge n-gram generation
  • aql: for running AQL query to prepare tokens for index
  • pipeline: for chaining multiple Analyzers
  • stopwords: removes the specified tokens from the input
  • geojson: breaks up a GeoJSON object into a set of indexable tokens
  • geopoint: breaks up a JSON object describing a coordinate into a set of indexable tokens

Available normalizations are case conversion and accent removal (conversion of characters with diacritical marks to the base characters).

Analyzer / FeatureTokenizationStemmingNormalizationN-grams
identityNoNoNoNo
delimiter(Yes)NoNoNo
stemNoYesNoNo
normNoNoYesNo
ngramNoNoNoYes
textYesYesYes(Yes)
aql(Yes)(Yes)(Yes)(Yes)
pipeline(Yes)(Yes)(Yes)(Yes)
stopwordsNoNoNoNo
geojson
geopoint

Analyzer Properties

The valid attributes/values for the properties are dependant on what type is used. For example, the delimiter type needs to know the desired delimiting character(s), whereas the text type takes a locale, stop-words and more.

identity

An Analyzer applying the identity transformation, i.e. returning the input unmodified.

It does not support any properties and will ignore them.

Examples

Applying the identity Analyzers does not perform any transformations, hence the input is returned unaltered:

  1. arangosh> db._query(`RETURN TOKENS("UPPER lower dïäcríticš", "identity")`).toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "UPPER lower dïäcríticš"
  4. ]
  5. ]

delimiter

An Analyzer capable of breaking up delimited text into tokens as per RFC 4180 (without starting new records on newlines).

The properties allowed for this Analyzer are an object with the following attributes:

  • delimiter (string): the delimiting character(s)

Examples

Split input strings into tokens at hyphen-minus characters:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("delimiter_hyphen", "delimiter", {
  3. ........> delimiter: "-"
  4. ........> }, ["frequency", "norm", "position"]);
  5. arangosh> db._query(`RETURN TOKENS("some-delimited-words", "delimiter_hyphen")`).toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "some",
  4. "delimited",
  5. "words"
  6. ]
  7. ]

stem

An Analyzer capable of stemming the text, treated as a single token, for supported languages.

The properties allowed for this Analyzer are an object with the following attributes:

  • locale (string): a locale in the format language[_COUNTRY][.encoding][@variant] (square brackets denote optional parts), e.g. "de.utf-8" or "en_US.utf-8". Only UTF-8 encoding is meaningful in ArangoDB. Also see Supported Languages.

Examples

Apply stemming to the input string as a whole:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("stem_en", "stem", {
  3. ........> locale: "en.utf-8"
  4. ........> }, ["frequency", "norm", "position"]);
  5. arangosh> db._query(`RETURN TOKENS("databases", "stem_en")`).toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "databas"
  4. ]
  5. ]

norm

An Analyzer capable of normalizing the text, treated as a single token, i.e. case conversion and accent removal.

The properties allowed for this Analyzer are an object with the following attributes:

  • locale (string): a locale in the format language[_COUNTRY][.encoding][@variant] (square brackets denote optional parts), e.g. "de.utf-8" or "en_US.utf-8". Only UTF-8 encoding is meaningful in ArangoDB. Also see Supported Languages.
  • accent (boolean, optional):
    • true to preserve accented characters (default)
    • false to convert accented characters to their base characters
  • case (string, optional):
    • "lower" to convert to all lower-case characters
    • "upper" to convert to all upper-case characters
    • "none" to not change character case (default)

Examples

Convert input string to all upper-case characters:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("norm_upper", "norm", {
  3. ........> locale: "en.utf-8",
  4. ........> case: "upper"
  5. ........> }, ["frequency", "norm", "position"]);
  6. arangosh> db._query(`RETURN TOKENS("UPPER lower dïäcríticš", "norm_upper")`).toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "UPPER LOWER DÏÄCRÍTICŠ"
  4. ]
  5. ]

Convert accented characters to their base characters:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("norm_accent", "norm", {
  3. ........> locale: "en.utf-8",
  4. ........> accent: false
  5. ........> }, ["frequency", "norm", "position"]);
  6. arangosh> db._query(`RETURN TOKENS("UPPER lower dïäcríticš", "norm_accent")`).toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "UPPER lower diacritics"
  4. ]
  5. ]

Convert input string to all lower-case characters and remove diacritics:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("norm_accent_lower", "norm", {
  3. ........> locale: "en.utf-8",
  4. ........> accent: false,
  5. ........> case: "lower"
  6. ........> }, ["frequency", "norm", "position"]);
  7. arangosh> db._query(`RETURN TOKENS("UPPER lower dïäcríticš", "norm_accent_lower")`).toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "upper lower diacritics"
  4. ]
  5. ]

ngram

An Analyzer capable of producing n-grams from a specified input in a range of min..max (inclusive). Can optionally preserve the original input.

This Analyzer type can be used to implement substring matching. Note that it slices the input based on bytes and not characters by default (streamType). The “binary” mode supports single-byte characters only; multi-byte UTF-8 characters raise an Invalid UTF-8 sequence query error.

The properties allowed for this Analyzer are an object with the following attributes:

  • min (number): unsigned integer for the minimum n-gram length
  • max (number): unsigned integer for the maximum n-gram length
  • preserveOriginal (boolean):
    • true to include the original value as well
    • false to produce the n-grams based on min and max only
  • startMarker (string, optional): this value will be prepended to n-grams which include the beginning of the input. Can be used for matching prefixes. Choose a character or sequence as marker which does not occur in the input.
  • endMarker (string, optional): this value will be appended to n-grams which include the end of the input. Can be used for matching suffixes. Choose a character or sequence as marker which does not occur in the input.
  • streamType (string, optional): type of the input stream
    • "binary": one byte is considered as one character (default)
    • "utf8": one Unicode codepoint is treated as one character

Examples

With min = 4 and max = 5, the Analyzer will produce the following n-grams for the input string "foobar":

  • "foob"
  • "fooba"
  • "foobar" (if preserveOriginal is enabled)
  • "ooba"
  • "oobar"
  • "obar"

An input string "foo" will not produce any n-gram unless preserveOriginal is enabled, because it is shorter than the min length of 4.

Above example but with startMarker = "^" and endMarker = "$" would produce the following:

  • "^foob"
  • "^fooba"
  • "^foobar" (if preserveOriginal is enabled)
  • "foobar$" (if preserveOriginal is enabled)
  • "ooba"
  • "oobar$"
  • "obar$"

Create and use a trigram Analyzer with preserveOriginal disabled:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("trigram", "ngram", {
  3. ........> min: 3,
  4. ........> max: 3,
  5. ........> preserveOriginal: false,
  6. ........> streamType: "utf8"
  7. ........> }, ["frequency", "norm", "position"]);
  8. arangosh> db._query(`RETURN TOKENS("foobar", "trigram")`).toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "foo",
  4. "oob",
  5. "oba",
  6. "bar"
  7. ]
  8. ]

Create and use a bigram Analyzer with preserveOriginal enabled and with start and stop markers:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("bigram_markers", "ngram", {
  3. ........> min: 2,
  4. ........> max: 2,
  5. ........> preserveOriginal: true,
  6. ........> startMarker: "^",
  7. ........> endMarker: "$",
  8. ........> streamType: "utf8"
  9. ........> }, ["frequency", "norm", "position"]);
  10. arangosh> db._query(`RETURN TOKENS("foobar", "bigram_markers")`).toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "^fo",
  4. "^foobar",
  5. "foobar$",
  6. "oo",
  7. "ob",
  8. "ba",
  9. "ar$"
  10. ]
  11. ]

text

An Analyzer capable of breaking up strings into individual words while also optionally filtering out stop-words, extracting word stems, applying case conversion and accent removal.

The properties allowed for this Analyzer are an object with the following attributes:

  • locale (string): a locale in the format language[_COUNTRY][.encoding][@variant] (square brackets denote optional parts), e.g. "de.utf-8" or "en_US.utf-8". Only UTF-8 encoding is meaningful in ArangoDB. Also see Supported Languages.
  • accent (boolean, optional):
    • true to preserve accented characters
    • false to convert accented characters to their base characters (default)
  • case (string, optional):
    • "lower" to convert to all lower-case characters (default)
    • "upper" to convert to all upper-case characters
    • "none" to not change character case
  • stemming (boolean, optional):
    • true to apply stemming on returned words (default)
    • false to leave the tokenized words as-is
  • edgeNgram (object, optional): if present, then edge n-grams are generated for each token (word). That is, the start of the n-gram is anchored to the beginning of the token, whereas the ngram Analyzer would produce all possible substrings from a single input token (within the defined length restrictions). Edge n-grams can be used to cover word-based auto-completion queries with an index, for which you should set the following other options: accent: false, case: "lower" and most importantly stemming: false.
    • min (number, optional): minimal n-gram length
    • max (number, optional): maximal n-gram length
    • preserveOriginal (boolean, optional): whether to include the original token even if its length is less than min or greater than max
  • stopwords (array, optional): an array of strings with words to omit from result. Default: load words from stopwordsPath. To disable stop-word filtering provide an empty array []. If both stopwords and stopwordsPath are provided then both word sources are combined.
  • stopwordsPath (string, optional): path with a language sub-directory (e.g. en for a locale en_US.utf-8) containing files with words to omit. Each word has to be on a separate line. Everything after the first whitespace character on a line will be ignored and can be used for comments. The files can be named arbitrarily and have any file extension (or none).

    Default: if no path is provided then the value of the environment variable IRESEARCH_TEXT_STOPWORD_PATH is used to determine the path, or if it is undefined then the current working directory is assumed. If the stopwords attribute is provided then no stop-words are loaded from files, unless an explicit stopwordsPath is also provided.

    Note that if the stopwordsPath can not be accessed, is missing language sub-directories or has no files for a language required by an Analyzer, then the creation of a new Analyzer is refused. If such an issue is discovered for an existing Analyzer during startup then the server will abort with a fatal error.

Examples

The built-in text_en Analyzer has stemming enabled (note the word endings):

  1. arangosh> db._query(`RETURN TOKENS("Crazy fast NoSQL-database!", "text_en")`).toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "crazi",
  4. "fast",
  5. "nosql",
  6. "databas"
  7. ]
  8. ]

You may create a custom Analyzer with the same configuration but with stemming disabled like this:

  1. arangosh> var analyzers = require("@arangodb/analyzers")
  2. arangosh> var a = analyzers.save("text_en_nostem", "text", {
  3. ........> locale: "en.utf-8",
  4. ........> case: "lower",
  5. ........> accent: false,
  6. ........> stemming: false,
  7. ........> stopwords: []
  8. ........> }, ["frequency","norm","position"])
  9. arangosh> db._query(`RETURN TOKENS("Crazy fast NoSQL-database!", "text_en_nostem")`).toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "crazy",
  4. "fast",
  5. "nosql",
  6. "database"
  7. ]
  8. ]

Custom text Analyzer with the edge n-grams feature and normalization enabled, stemming disabled and "the" defined as stop-word to exclude it:

  1. arangosh> var a = analyzers.save("text_edge_ngrams", "text", {
  2. ........> edgeNgram: { min: 3, max: 8, preserveOriginal: true },
  3. ........> locale: "en.utf-8",
  4. ........> case: "lower",
  5. ........> accent: false,
  6. ........> stemming: false,
  7. ........> stopwords: [ "the" ]
  8. ........> }, ["frequency","norm","position"])
  9. arangosh> db._query(`RETURN TOKENS(
  10. ........> "The quick brown fox jumps over the dogWithAVeryLongName",
  11. ........> "text_edge_ngrams"
  12. ........> )`).toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "qui",
  4. "quic",
  5. "quick",
  6. "bro",
  7. "brow",
  8. "brown",
  9. "fox",
  10. "jum",
  11. "jump",
  12. "jumps",
  13. "ove",
  14. "over",
  15. "dog",
  16. "dogw",
  17. "dogwi",
  18. "dogwit",
  19. "dogwith",
  20. "dogwitha",
  21. "dogwithaverylongname"
  22. ]
  23. ]

aql

Introduced in: v3.8.0

An Analyzer capable of running a restricted AQL query to perform data manipulation / filtering.

The query must not access the storage engine. This means no FOR loops over collections or Views, no use of the DOCUMENT() function, no graph traversals. AQL functions are allowed as long as they do not involve Analyzers (TOKENS(), PHRASE(), NGRAM_MATCH(), ANALYZER() etc.) or data access, and if they can be run on DB-Servers in case of a cluster deployment. User-defined functions are not permitted.

The input data is provided to the query via a bind parameter @param. It is always a string. The AQL query is invoked for each token in case of multiple input tokens, such as an array of strings.

The output can be one or multiple tokens (top-level result elements). They get converted to the configured returnType, either booleans, numbers or strings (default).

If returnType is "number" or "bool" then it is unnecessary to set this AQL Analyzer as context Analyzer with ANALYZER() in View queries. You can compare indexed fields to numeric values, true or false directly, because they bypass Analyzer processing.

The properties allowed for this Analyzer are an object with the following attributes:

  • queryString (string): AQL query to be executed
  • collapsePositions (boolean):
    • true: set the position to 0 for all members of the query result array
    • false (default): set the position corresponding to the index of the result array member
  • keepNull (boolean):
    • true (default): treat null like an empty string
    • false: discard nulls from View index. Can be used for index filtering (i.e. make your query return null for unwanted data). Note that empty results are always discarded.
  • batchSize (integer): number between 1 and 1000 (default = 1) that determines the batch size for reading data from the query. In general, a single token is expected to be returned. However, if the query is expected to return many results, then increasing batchSize trades memory for performance.
  • memoryLimit (integer): memory limit for query execution in bytes. (default is 1048576 = 1Mb) Maximum is 33554432U (32Mb)
  • returnType (string): data type of the returned tokens. If the indicated type does not match the actual type then an implicit type conversion is applied (see TO_STRING(), TO_NUMBER(), TO_BOOL())
    • "string" (default): convert emitted tokens to strings
    • "number": convert emitted tokens to numbers
    • "bool": convert emitted tokens to booleans

Examples

Soundex Analyzer for a phonetically similar term search:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("soundex", "aql", { queryString: "RETURN SOUNDEX(@param)" },
  3. ........> ["frequency", "norm", "position"]);
  4. arangosh> db._query("RETURN TOKENS('ArangoDB', 'soundex')").toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "A652"
  4. ]
  5. ]

Concatenating Analyzer for conditionally adding a custom prefix or suffix:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("concat", "aql", { queryString:
  3. ........> "RETURN LOWER(LEFT(@param, 5)) == 'inter' ? CONCAT(@param, 'ism') : CONCAT('inter', @param)"
  4. ........> }, ["frequency", "norm", "position"]);
  5. arangosh> db._query("RETURN TOKENS('state', 'concat')");
  6. arangosh> db._query("RETURN TOKENS('international', 'concat')");

Show execution results

Hide execution results

  1. [
  2. [
  3. "interstate"
  4. ]
  5. ]
  6. [object ArangoQueryCursor, count: 1, cached: false, hasMore: false]
  7. [
  8. [
  9. "internationalism"
  10. ]
  11. ]
  12. [object ArangoQueryCursor, count: 1, cached: false, hasMore: false]

Filtering Analyzer that ignores unwanted data based on the prefix "ir", with keepNull: false and explicitly returning null:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("filter", "aql", { keepNull: false, queryString:
  3. ........> "RETURN LOWER(LEFT(@param, 2)) == 'ir' ? null : @param"
  4. ........> }, ["frequency", "norm", "position"]);
  5. arangosh> db._query("RETURN TOKENS('regular', 'filter')");
  6. arangosh> db._query("RETURN TOKENS('irregular', 'filter')");

Show execution results

Hide execution results

  1. [
  2. [
  3. "regular"
  4. ]
  5. ]
  6. [object ArangoQueryCursor, count: 1, cached: false, hasMore: false]
  7. [
  8. [ ]
  9. ]
  10. [object ArangoQueryCursor, count: 1, cached: false, hasMore: false]

Filtering Analyzer that discards unwanted data based on the prefix "ir", using a filter for an empty result, which is discarded from the View index even without keepNull: false:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("filter", "aql", { queryString:
  3. ........> "FILTER LOWER(LEFT(@param, 2)) != 'ir' RETURN @param"
  4. ........> }, ["frequency", "norm", "position"]);
  5. arangosh> var coll = db._create("coll");
  6. arangosh> var doc1 = db.coll.save({ value: "regular" });
  7. arangosh> var doc2 = db.coll.save({ value: "irregular" });
  8. arangosh> var view = db._createView("view", "arangosearch",
  9. ........> { links: { coll: { fields: { value: { analyzers: ["filter"] }}}}})
  10. arangosh> db._query("FOR doc IN view SEARCH ANALYZER(doc.value IN ['regular', 'irregular'], 'filter') RETURN doc");

Show execution results

Hide execution results

  1. [
  2. {
  3. "_key" : "69909",
  4. "_id" : "coll/69909",
  5. "_rev" : "_cuv9a3q--_",
  6. "value" : "regular"
  7. }
  8. ]
  9. [object ArangoQueryCursor, count: 1, cached: false, hasMore: false]

Custom tokenization with collapsePositions on and off: The input string "A-B-C-D" is split into an array of strings ["A", "B", "C", "D"]. The position metadata (as used by the PHRASE() function) is set to 0 for all four strings if collapsePosition is enabled. Otherwise the position is set to the respective array index, 0 for "A", 1 for "B" and so on.

collapsePositionABCD
true0000
false0123
  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a1 = analyzers.save("collapsed", "aql", { collapsePositions: true, queryString:
  3. ........> "FOR d IN SPLIT(@param, '-') RETURN d"
  4. ........> }, ["frequency", "norm", "position"]);
  5. arangosh> var a2 = analyzers.save("uncollapsed", "aql", { collapsePositions: false, queryString:
  6. ........> "FOR d IN SPLIT(@param, '-') RETURN d"
  7. ........> }, ["frequency", "norm", "position"]);
  8. arangosh> var coll = db._create("coll");
  9. arangosh> var view = db._createView("view", "arangosearch",
  10. ........> { links: { coll: { analyzers: [ "collapsed", "uncollapsed" ], includeAllFields: true }}});
  11. arangosh> var doc = db.coll.save({ text: "A-B-C-D" });
  12. arangosh> db._query("FOR d IN view SEARCH PHRASE(d.text, {TERM: 'B'}, 1, {TERM: 'D'}, 'uncollapsed') RETURN d");
  13. arangosh> db._query("FOR d IN view SEARCH PHRASE(d.text, {TERM: 'B'}, -1, {TERM: 'D'}, 'uncollapsed') RETURN d");
  14. arangosh> db._query("FOR d IN view SEARCH PHRASE(d.text, {TERM: 'B'}, 1, {TERM: 'D'}, 'collapsed') RETURN d");
  15. arangosh> db._query("FOR d IN view SEARCH PHRASE(d.text, {TERM: 'B'}, -1, {TERM: 'D'}, 'collapsed') RETURN d");

Show execution results

Hide execution results

  1. [
  2. {
  3. "_key" : "69871",
  4. "_id" : "coll/69871",
  5. "_rev" : "_cuv9ay2---",
  6. "text" : "A-B-C-D"
  7. }
  8. ]
  9. [object ArangoQueryCursor, count: 1, cached: false, hasMore: false]
  10. [
  11. {
  12. "_key" : "69871",
  13. "_id" : "coll/69871",
  14. "_rev" : "_cuv9ay2---",
  15. "text" : "A-B-C-D"
  16. }
  17. ]
  18. [object ArangoQueryCursor, count: 1, cached: false, hasMore: false]
  19. [object ArangoQueryCursor, count: 0, cached: false, hasMore: false]
  20. [
  21. {
  22. "_key" : "69871",
  23. "_id" : "coll/69871",
  24. "_rev" : "_cuv9ay2---",
  25. "text" : "A-B-C-D"
  26. }
  27. ]
  28. [object ArangoQueryCursor, count: 1, cached: false, hasMore: false]

The position data is not directly exposed, but we can see its effects through the PHRASE() function. There is one token between "B" and "D" to skip in case of uncollapsed positions. With positions collapsed, both are in the same position, thus there is negative one to skip to match the tokens.

pipeline

Introduced in: v3.8.0

An Analyzer capable of chaining effects of multiple Analyzers into one. The pipeline is a list of Analyzers, where the output of an Analyzer is passed to the next for further processing. The final token value is determined by last Analyzer in the pipeline.

The Analyzer is designed for cases like the following:

  • Normalize text for a case insensitive search and apply n-gram tokenization
  • Split input with delimiter Analyzer, followed by stemming with the stem Analyzer

The properties allowed for this Analyzer are an object with the following attributes:

  • pipeline (array): an array of Analyzer definition-like objects with type and properties attributes

Analyzers of types geopoint and geojson cannot be used in pipelines and will make the creation fail. These Analyzers require additional postprocessing and can only be applied to document fields directly.

Examples

Normalize to all uppercase and compute bigrams:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("ngram_upper", "pipeline", { pipeline: [
  3. ........> { type: "norm", properties: { locale: "en.utf-8", case: "upper" } },
  4. ........> { type: "ngram", properties: { min: 2, max: 2, preserveOriginal: false, streamType: "utf8" } }
  5. ........> ] }, ["frequency", "norm", "position"]);
  6. arangosh> db._query(`RETURN TOKENS("Quick brown foX", "ngram_upper")`).toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "QU",
  4. "UI",
  5. "IC",
  6. "CK",
  7. "K ",
  8. " B",
  9. "BR",
  10. "RO",
  11. "OW",
  12. "WN",
  13. "N ",
  14. " F",
  15. "FO",
  16. "OX"
  17. ]
  18. ]

Split at delimiting characters , and ;, then stem the tokens:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("delimiter_stem", "pipeline", { pipeline: [
  3. ........> { type: "delimiter", properties: { delimiter: "," } },
  4. ........> { type: "delimiter", properties: { delimiter: ";" } },
  5. ........> { type: "stem", properties: { locale: "en.utf-8" } }
  6. ........> ] }, ["frequency", "norm", "position"]);
  7. arangosh> db._query(`RETURN TOKENS("delimited,stemmable;words", "delimiter_stem")`).toArray();

Show execution results

Hide execution results

  1. [
  2. [
  3. "delimit",
  4. "stemmabl",
  5. "word"
  6. ]
  7. ]

stopwords

Introduced in: v3.8.1

An Analyzer capable of removing specified tokens from the input.

It uses binary comparison to determine if an input token should be discarded. It checks for exact matches. If the input contains only a substring that matches one of the defined stopwords, then it is not discarded. Longer inputs such as prefixes of stopwords are also not discarded.

The properties allowed for this Analyzer are an object with the following attributes:

  • stopwords (array): array of strings that describe the tokens to be discarded. The interpretation of each string depends on the value of the hex parameter.
  • hex (boolean): If false (default), then each string in stopwords is used verbatim. If true, then the strings need to be hex-encoded. This allows for removing tokens that contain non-printable characters. To encode UTF-8 strings to hex strings you can use e.g.

    • AQL:

      1. FOR token IN ["and","the"] RETURN TO_HEX(token)
    • arangosh / Node.js:

      1. ["and","the"].map(token => Buffer(token).toString("hex"))
    • Modern browser:

      1. ["and","the"].map(token => Array.from(new TextEncoder().encode(token), byte => byte.toString(16).padStart(2, "0")).join(""))

Examples

Create and use a stopword Analyzer that removes the tokens and and the. The stopword array with hex-encoded strings for this looks like ["616e64","746865"] (a = 0x61, n = 0x6e, d = 0x64 and so on). Note that a and theater are not removed, because there is no exact match with either of the stopwords and and the:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("stop", "stopwords", {
  3. ........> stopwords: ["616e64","746865"], hex: true
  4. ........> }, ["frequency", "norm"]);
  5. arangosh> db._query("RETURN FLATTEN(TOKENS(SPLIT('the fox and the dog and a theater', ' '), 'stop'))");

Show execution results

Hide execution results

  1. [
  2. [
  3. "fox",
  4. "dog",
  5. "a",
  6. "theater"
  7. ]
  8. ]
  9. [object ArangoQueryCursor, count: 1, cached: false, hasMore: false]

Create and use an Analyzer pipeline that normalizes the input (convert to lower-case and base characters) and then discards the stopwords and and the:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("norm_stop", "pipeline", { "pipeline": [
  3. ........> { type: "norm", properties: { locale: "en.utf-8", accent: false, case: "lower" } },
  4. ........> { type: "stopwords", properties: { stopwords: ["and","the"], hex: false } },
  5. ........> ]}, ["frequency", "norm"]);
  6. arangosh> db._query("RETURN FLATTEN(TOKENS(SPLIT('The fox AND the dog äñḏ a ţhéäter', ' '), 'norm_stop'))");

Show execution results

Hide execution results

  1. [
  2. [
  3. "fox",
  4. "dog",
  5. "a",
  6. "theater"
  7. ]
  8. ]
  9. [object ArangoQueryCursor, count: 1, cached: false, hasMore: false]

geojson

Introduced in: v3.8.0

An Analyzer capable of breaking up a GeoJSON object into a set of indexable tokens for further usage with ArangoSearch Geo functions.

GeoJSON object example:

  1. {
  2. "type": "Point",
  3. "coordinates": [ -73.97, 40.78 ] // [ longitude, latitude ]
  4. }

The properties allowed for this Analyzer are an object with the following attributes:

  • type (string, optional):
    • "shape" (default): index all GeoJSON geometry types (Point, Polygon etc.)
    • "centroid": compute and only index the centroid of the input geometry
    • "point": only index GeoJSON objects of type Point, ignore all other geometry types
  • options (object, optional): options for fine-tuning geo queries. These options should generally remain unchanged
    • maxCells (number, optional): maximum number of S2 cells (default: 20)
    • minLevel (number, optional): the least precise S2 level (default: 4)
    • maxLevel (number, optional): the most precise S2 level (default: 23)

Examples

Create a collection with GeoJSON Points stored in an attribute location, a geojson Analyzer with default properties, and a View using the Analyzer. Then query for locations that are within a 3 kilometer radius of a given point and return the matched documents, including the calculated distance in meters. The stored coordinates and the GEO_POINT() arguments are expected in longitude, latitude order:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("geo_json", "geojson", {}, ["frequency", "norm", "position"]);
  3. arangosh> db._create("geo");
  4. arangosh> db.geo.save([
  5. ........> { location: { type: "Point", coordinates: [6.937, 50.932] } },
  6. ........> { location: { type: "Point", coordinates: [6.956, 50.941] } },
  7. ........> { location: { type: "Point", coordinates: [6.962, 50.932] } },
  8. ........> ]);
  9. arangosh> db._createView("geo_view", "arangosearch", {
  10. ........> links: {
  11. ........> geo: {
  12. ........> fields: {
  13. ........> location: {
  14. ........> analyzers: ["geo_json"]
  15. ........> }
  16. ........> }
  17. ........> }
  18. ........> }
  19. ........> });
  20. arangosh> db._query(`LET point = GEO_POINT(6.93, 50.94)
  21. ........> FOR doc IN geo_view
  22. ........> SEARCH ANALYZER(GEO_DISTANCE(doc.location, point) < 2000, "geo_json")
  23. ........> RETURN MERGE(doc, { distance: GEO_DISTANCE(doc.location, point) })`).toArray();

Show execution results

Hide execution results

  1. [ArangoCollection 69966, "geo" (type document, status loaded)]
  2. [
  3. {
  4. "_id" : "geo/69971",
  5. "_key" : "69971",
  6. "_rev" : "_cuv9a7u---"
  7. },
  8. {
  9. "_id" : "geo/69972",
  10. "_key" : "69972",
  11. "_rev" : "_cuv9a7u--_"
  12. },
  13. {
  14. "_id" : "geo/69973",
  15. "_key" : "69973",
  16. "_rev" : "_cuv9a7u--A"
  17. }
  18. ]
  19. [ArangoView 69974, "geo_view" (type arangosearch)]
  20. [
  21. {
  22. "_id" : "geo/69971",
  23. "_key" : "69971",
  24. "_rev" : "_cuv9a7u---",
  25. "location" : {
  26. "type" : "Point",
  27. "coordinates" : [
  28. 6.937,
  29. 50.932
  30. ]
  31. },
  32. "distance" : 1015.8355739436823
  33. },
  34. {
  35. "_id" : "geo/69972",
  36. "_key" : "69972",
  37. "_rev" : "_cuv9a7u--_",
  38. "location" : {
  39. "type" : "Point",
  40. "coordinates" : [
  41. 6.956,
  42. 50.941
  43. ]
  44. },
  45. "distance" : 1825.1307183571266
  46. }
  47. ]

geopoint

Introduced in: v3.8.0

An Analyzer capable of breaking up JSON object describing a coordinate into a set of indexable tokens for further usage with ArangoSearch Geo functions.

The Analyzer can be used for two different coordinate representations:

  • an array with two numbers as elements in the format [<latitude>, <longitude>], e.g. [40.78, -73.97].
  • two separate number attributes, one for latitude and one for longitude, e.g. { location: { lat: 40.78, lon: -73.97 } }. The attributes cannot be at the top level of the document, but must be nested like in the example, so that the Analyzer can be defined for the field location with the Analyzer properties { "latitude": ["lat"], "longitude": ["lng"] }.

The properties allowed for this Analyzer are an object with the following attributes:

  • latitude (array, optional): array of strings that describes the attribute path of the latitude value relative to the field for which the Analyzer is defined in the View
  • longitude (array, optional): array of strings that describes the attribute path of the longitude value relative to the field for which the Analyzer is defined in the View
  • options (object, optional): options for fine-tuning geo queries. These options should generally remain unchanged
    • maxCells (number, optional): maximum number of S2 cells (default: 20)
    • minLevel (number, optional): the least precise S2 level (default: 4)
    • maxLevel (number, optional): the most precise S2 level (default: 23)

Examples

Create a collection with coordinates pairs stored in an attribute location, a geopoint Analyzer with default properties, and a View using the Analyzer. Then query for locations that are within a 3 kilometer radius of a given point. The stored coordinates are in latitude, longitude order, but GEO_POINT() and GEO_DISTANCE() expect longitude, latitude order:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("geo_pair", "geopoint", {}, ["frequency", "norm", "position"]);
  3. arangosh> db._create("geo");
  4. arangosh> db.geo.save([
  5. ........> { location: [50.932, 6.937] },
  6. ........> { location: [50.941, 6.956] },
  7. ........> { location: [50.932, 6.962] },
  8. ........> ]);
  9. arangosh> db._createView("geo_view", "arangosearch", {
  10. ........> links: {
  11. ........> geo: {
  12. ........> fields: {
  13. ........> location: {
  14. ........> analyzers: ["geo_pair"]
  15. ........> }
  16. ........> }
  17. ........> }
  18. ........> }
  19. ........> });
  20. arangosh> db._query(`LET point = GEO_POINT(6.93, 50.94)
  21. ........> FOR doc IN geo_view
  22. ........> SEARCH ANALYZER(GEO_DISTANCE(doc.location, point) < 2000, "geo_pair")
  23. ........> RETURN MERGE(doc, { distance: GEO_DISTANCE([doc.location[1], doc.location[0]], point) })`).toArray();

Show execution results

Hide execution results

  1. [ArangoCollection 70016, "geo" (type document, status loaded)]
  2. [
  3. {
  4. "_id" : "geo/70021",
  5. "_key" : "70021",
  6. "_rev" : "_cuv9bAe---"
  7. },
  8. {
  9. "_id" : "geo/70022",
  10. "_key" : "70022",
  11. "_rev" : "_cuv9bAe--_"
  12. },
  13. {
  14. "_id" : "geo/70023",
  15. "_key" : "70023",
  16. "_rev" : "_cuv9bAe--A"
  17. }
  18. ]
  19. [ArangoView 70024, "geo_view" (type arangosearch)]
  20. [
  21. {
  22. "_id" : "geo/70021",
  23. "_key" : "70021",
  24. "_rev" : "_cuv9bAe---",
  25. "location" : [
  26. 50.932,
  27. 6.937
  28. ],
  29. "distance" : 1015.8355739436823
  30. },
  31. {
  32. "_id" : "geo/70022",
  33. "_key" : "70022",
  34. "_rev" : "_cuv9bAe--_",
  35. "location" : [
  36. 50.941,
  37. 6.956
  38. ],
  39. "distance" : 1825.1307183571266
  40. }
  41. ]

Create a collection with coordinates stored in an attribute location as separate nested attributes lat and lng, a geopoint Analyzer that specifies the attribute paths to the latitude and longitude attributes (relative to location attribute), and a View using the Analyzer. Then query for locations that are within a 3 kilometer radius of a given point:

  1. arangosh> var analyzers = require("@arangodb/analyzers");
  2. arangosh> var a = analyzers.save("geo_latlng", "geopoint", {
  3. ........> latitude: ["lat"],
  4. ........> longitude: ["lng"]
  5. ........> }, ["frequency", "norm", "position"]);
  6. arangosh> db._create("geo");
  7. arangosh> db.geo.save([
  8. ........> { location: { lat: 50.932, lng: 6.937 } },
  9. ........> { location: { lat: 50.941, lng: 6.956 } },
  10. ........> { location: { lat: 50.932, lng: 6.962 } },
  11. ........> ]);
  12. arangosh> db._createView("geo_view", "arangosearch", {
  13. ........> links: {
  14. ........> geo: {
  15. ........> fields: {
  16. ........> location: {
  17. ........> analyzers: ["geo_latlng"]
  18. ........> }
  19. ........> }
  20. ........> }
  21. ........> }
  22. ........> });
  23. arangosh> db._query(`LET point = GEO_POINT(6.93, 50.94)
  24. ........> FOR doc IN geo_view
  25. ........> SEARCH ANALYZER(GEO_DISTANCE(doc.location, point) < 2000, "geo_latlng")
  26. ........> RETURN MERGE(doc, { distance: GEO_DISTANCE([doc.location.lng, doc.location.lat], point) })`).toArray();

Show execution results

Hide execution results

  1. [ArangoCollection 69991, "geo" (type document, status loaded)]
  2. [
  3. {
  4. "_id" : "geo/69996",
  5. "_key" : "69996",
  6. "_rev" : "_cuv9b-O---"
  7. },
  8. {
  9. "_id" : "geo/69997",
  10. "_key" : "69997",
  11. "_rev" : "_cuv9b-O--_"
  12. },
  13. {
  14. "_id" : "geo/69998",
  15. "_key" : "69998",
  16. "_rev" : "_cuv9b-O--A"
  17. }
  18. ]
  19. [ArangoView 69999, "geo_view" (type arangosearch)]
  20. [
  21. {
  22. "_id" : "geo/69996",
  23. "_key" : "69996",
  24. "_rev" : "_cuv9b-O---",
  25. "location" : {
  26. "lat" : 50.932,
  27. "lng" : 6.937
  28. },
  29. "distance" : 1015.8355739436823
  30. },
  31. {
  32. "_id" : "geo/69997",
  33. "_key" : "69997",
  34. "_rev" : "_cuv9b-O--_",
  35. "location" : {
  36. "lat" : 50.941,
  37. "lng" : 6.956
  38. },
  39. "distance" : 1825.1307183571266
  40. }
  41. ]

Analyzer Features

The features of an Analyzer determine what term matching capabilities will be available and as such are only applicable in the context of ArangoSearch Views.

The valid values for the features are dependant on both the capabilities of the underlying type and the query filtering and sorting functions that the result can be used with. For example the text type will produce frequency + norm + position and the PHRASE() AQL function requires frequency + position to be available.

Currently the following features are supported:

  • frequency: how often a term is seen, required for PHRASE()
  • norm: the field normalization factor
  • position: sequentially increasing term position, required for PHRASE(). If present then the frequency feature is also required

Built-in Analyzers

There is a set of built-in Analyzers which are available by default for convenience and backward compatibility. They can not be removed.

The identity Analyzer has no properties and the features frequency and norm. The Analyzers of type text all tokenize strings with stemming enabled, no stopwords configured, accent removal and case conversion to lowercase turned on and the features frequency, norm and position:

NameTypeLocale (Language)CaseAccentStemmingStopwordsFeatures
identityidentity     [“frequency”, “norm”]
text_detextde.utf-8 (German)lowerfalsetrue[ ][“frequency”, “norm”, “position”]
text_entexten.utf-8 (English)lowerfalsetrue[ ][“frequency”, “norm”, “position”]
text_estextes.utf-8 (Spanish)lowerfalsetrue[ ][“frequency”, “norm”, “position”]
text_fitextfi.utf-8 (Finnish)lowerfalsetrue[ ][“frequency”, “norm”, “position”]
text_frtextfr.utf-8 (French)lowerfalsetrue[ ][“frequency”, “norm”, “position”]
text_ittextit.utf-8 (Italian)lowerfalsetrue[ ][“frequency”, “norm”, “position”]
text_nltextnl.utf-8 (Dutch)lowerfalsetrue[ ][“frequency”, “norm”, “position”]
text_notextno.utf-8 (Norwegian)lowerfalsetrue[ ][“frequency”, “norm”, “position”]
text_pttextpt.utf-8 (Portuguese)lowerfalsetrue[ ][“frequency”, “norm”, “position”]
text_rutextru.utf-8 (Russian)lowerfalsetrue[ ][“frequency”, “norm”, “position”]
text_svtextsv.utf-8 (Swedish)lowerfalsetrue[ ][“frequency”, “norm”, “position”]
text_zhtextzh.utf-8 (Chinese)lowerfalsetrue[ ][“frequency”, “norm”, “position”]

Note that locale, case, accent, stemming and stopwords are Analyzer properties. text_zh does not have actual stemming support for Chinese despite what the property value suggests.

Supported Languages

Analyzers rely on ICU for language-dependent tokenization and normalization. The ICU data file icudtl.dat that ArangoDB ships with contains information for a lot of languages, which are technically all supported.

The alphabetical order of characters is not taken into account by ArangoSearch, i.e. range queries in SEARCH operations against Views will not follow the language rules as per the defined Analyzer locale nor the server language (startup option --default-language)! Also see Known Issues.

Stemming support is provided by Snowball, which supports the following languages:

LanguageCode
Arabic ar
Basque eu
Catalan ca
Danish da
Dutchnl
Englishen
Finnishfi
Frenchfr
Germande
Greek el
Hindi hi
Hungarian hu
Indonesian id
Irish ga
Italianit
Lithuanian lt
Nepali ne
Norwegianno
Portuguesept
Romanian ro
Russianru
Serbian sr
Spanishes
Swedishsv
Tamil ta
Turkish *tr

* Introduced in: v3.7.0