Skip to main content
Previous section   Next section

iFind Search Tool

This chapter describes the iFind search facility, a tool for performing context-aware text search operations. To use iFind you must define an iFind index for each column containing text that you wish to search. You can then search the text records using a standard SQL query with a WHERE clause containing iFind SQL search syntax. The query will return all records that contain the specified search item or items. You can also highlight the matching text in the returned records.

Note:

To use iFind you must have a Caché license that provides access to iKnow. (You can view the licence key from the Management Portal: select System Administration then Licensing.)

Indexing Sources for iFind Search

You can use iFind to search SQL text in %String data type or %Stream.GlobalCharacter (character stream) data type.

To perform an iFind search, the column to be searched must have a defined iFind bitmap index. There are three levels of iFind indexes. These levels are defined in nested subclasses. Each index level provides all of the features of the previous level, plus additional iFind features specific to that level. You can create any of the following iFind index types:

Each index level supports all of the parameters of the previous level, and adds one or more additional parameters. Unspecified parameters take default values.

The following Class Definition example creates a table with a Semantic index on the Narrative property (column). The indexed property can be of data type %String or %Stream.GlobalCharacter:

   Class Aviation.TestSQLSrch Extends %Persistent [ 
      DdlAllowed,Owner={UnknownUser},SqlRowIdPrivate,
      SqlTableName=TestSQLSrch ]
  { 
  Property UniqueNum As %Integer;
  Property CrashDate As %TimeStamp [ SqlColumnNumber=2 ];
  Property Narrative As %String(MAXLEN=100000) [ SqlColumnNumber=3 ];
  Index NarrSemanticIdx On (Narrative) As %iFind.Index.Semantic(INDEXOPTION=0,
     LANGUAGE="en",LOWER=1);
  Index UniqueNumIdx On UniqueNum [ Type=index,Unique ];
  }
Copy code to clipboard

An iFind index of any type includes support for the following parameters:

  • INDEXOPTION specifies whether or not to index to allow for stemming or decompounding. Because indexing to support these operations significantly increases the size of the index, it is recommended that you specify INDEXOPTION=0 unless stemming or decompounding will very likely be used. The default is 0.

  • LANGUAGE specifies the language to use when indexing records. For example, "en" specifies English. Use "*" to enable automatic language identification. The default is "en".

  • LOWER specifies whether query search is case-sensitive. By default, iFind indexing is not case-sensitive; iFind normalizes the text to lowercase before indexing it. The LOWER parameter determines whether or not to perform this lowercase normalization (LOWER=1, the default, normalizes to lowercase). Because language conventions commonly capitalize words at the beginning of a sentence or when used in a title, normalizing to lowercase is preferable in most applications. If you specify LOWER=0, the query search_items string is case-sensitive. For example, if you specify LOWER=0, the query search_items string ‘turkey’ will only match turkey and not Turkey. If you specify LOWER=1, the query search_items string ‘turkey’ will match both turkey and Turkey.

  • USERDICTIONARY allows you to specify the name of a user-defined UserDictionary that is applied to the texts before indexing. This parameter is optional and is for advanced use only.

For a full list of supported parameters refer to %iFind.Index.Basic in the InterSystems Class Reference.

A Semantic index (%iFind.Index.Semantic) also supports the following optional parameter:

  • IFINDATTRIBUTES allows you to specify whether or not to identify negation in the text and store the negation attribute. IFINDATTRIBUTES=1 identifies and indexes negation. The default is IFINDATTRIBUTES=0.

Indexing a JSON Object

You can create an iFind index for text stored in a JSON object. This index specifies the starting position in the JSON structure. iFind recursively indexes all text at that level and all nested levels below it. Specify $ to index the entire JSON object. Specify $.key2 to index the JSON values at key2 and below.

Populating a Table

Like any SQL index, a defined iFind index (by default) is built when you populate a new table, and maintained when you subsequently insert, update, or delete data. You can defer building of an index when populating a table using %NOINDEX, and then use the %Build() method to build the index. You can add an index to a table that is already populated with data and then build that index. Refer to Defining and Building Indices for further details.

The following example populates the Aviation.TestIFind table from the Aviation.Events table in the Samples namespace. This example inserts a large amount of text, so running it may take a minute or so:

INSERT OR UPDATE INTO Aviation.TestIFind (UniqueNum,CrashDate,Narrative) 
    SELECT %ID,EventDate,NarrativeFull FROM Aviation.Event
Copy code to clipboard

This example uses INSERT OR UPDATE with a field defined with a unique key to prevent repeated execution from creating duplicate records.

Performing iFind Search

You use iFind syntax in an SQL query WHERE clause to perform a text search for one or more text items. These text items may be words or sequences of words (Basic index) or iKnow semantic entities (Semantic index). Multiple text items are an implicit AND search; all of the specified items must appear in the text, in any order. The syntax for iFind search is as follows:

WHERE %ID %FIND search_index(indexname,'search_items',search_option,'language')
  • indexname is the name of a defined iFind index for a specific column.

  • search_items is the list of text items (either words or iKnow entities) to search for, enclosed with quotes. Text items are separated by spaces. An item consists of an alphanumeric string and optional wildcard syntax characters. Text items are not case-sensitive. Available search_items syntax is described below.

  • search_option is the index option integer that specifies the type of search to perform. Available values include 0 (syntax search), 1 (syntax search with stemming), 2 (syntax search with decompounding and stemming), 3 (syntax search with fuzzy search), and 4 (syntax search with regular expressions). If search_option=4, search_items is assumed to contain a single Regular Expression string. For further details, refer to the Regular Expressions chapter in Using ObjectScript. Note that for performance reasons, iFind does not support some of the more esoteric regular expression syntactic forms; these syntactic forms are supported by the $LOCATE ObjectScript function.

  • language is the iKnow-supported language model to apply, specified as a two-character string. For example, 'en' specifies English. If you specify '*', the query performs automatic language identification.

When performing an Basic index search, iFind identifies words by the presence of one or more space characters. Sentence punctuation (a period, comma, semicolon, or colon followed by a space) is ignored. iFind treats all other punctuation as literals. For example, iFind treats “touch-and-go” as a single word. Punctuation such as hyphens or a decimal point in a number are treated as literals. Quote characters and apostrophes must be specified. You specify a single quote character by doubling it.

You can perform any Basic index search (word, co-occurrence, or positional phrase) with a Semantic index. Attempting to perform a Semantic index search with a Basic index results in an SQLCODE -149 error.

SQL search_items Syntax

Basic index search_items can contain the following syntax:

Word Search:

word1 word2 word3 Specifies that these exact words must appear (in any order) somewhere in the text. (Logical AND). You can specify a single word, or any number of words separated by spaces.
word1 OR word2 NOT word3
word1 OR (word2 AND word3)
search_items can contain AND, OR, and NOT logical operators. AND is the same as separating words with spaces (implicit AND). NOT is logically equivalent to AND NOT. search_items can also use parentheses to group logical operators. Explicit AND is needed when specifying multiple words in grouping parentheses: (word2 AND word3). If the explicit AND was omitted, (word2 word3) would be interpreted as a positional phrase. You can use the \ escape character to specify AND, OR, NOT as literals rather than logical operators: \and
*word
word*
*word*
w*d
An asterisk wildcard specifies 0 or more non-space characters of any type. An asterisk can be used as a prefix, suffix, or within a word. You can use \ escape character to specify * as a literal: \*

Co-occurrence Word Search:

[word1,word2,...,range]
Co-occurrence search. Specifies that these exact words must appear (in any order) within the proximity window specified by range. You can specify any number of words or multi-word phrases. A multi-word phrase is specified as words separated by spaces with no delimiting punctuation. Words (or positional phrases) are separated by commas, the last comma-separated element is an optional numeric range. Words can specify asterisk wildcards.
A range can be specified as min–max or simply as max with a default min of 1. For example, 1–5 or 5. range is optional; if omitted, it defaults to 1–20. A range count is inclusive of all of the specified words.
Co-occurrence search cannot be used with search_option=4 (Regular Expressions).

Positional Phrase Search:

Note:

You can use double quotes "word1 word2 word3" or parentheses (word1 word2 word3) to delimit a positional phrase. Because parentheses are also used to group logical operators, the use of double quotes is preferred.

"word1 word2 word3"
These exact words must appear sequentially in the specified order. Words are separated by spaces. Note that no semantic analysis is performed; for example, the words in a “phrase” may be the final word of a sentence and the beginning words of the next sentence. Asterisk wildcards can be applied to individual words in a phrase. A literal parentheses character in the search_items must be enclosed with quotes.
"word1 ? word3"
"word1 ? ? ? word5"
A question mark indicates that exactly one word is found between the specified words in a phrase. You can specify multiple single question marks, each separated by spaces.
"word1 ?? word6"
A double question mark (with no space between) indicates that from 0 to 6 words are found between the specified words in a phrase.
"word1 [1–3] word5"
Square brackets indicate an interval number of words between the specified words in a phrase: min-max. This interval is specified as a variable range, in this case from 1 to 3 missing words.

Semantic index search_items can contain the following iKnow entity search syntax in addition to the Basic index syntax:

Full Entity and Partial Entity Search:

{entity} Specifies the exact wording of an iKnow entity. Asterisk wildcards can be applied to individual words in an entity.
<{entity} A less-than sign prefix specifies an iKnow entity ending with the specified word(s). There must be one or more words in the entity appearing before the specified word(s).
{entity}> A greater-than sign suffix specifies an iKnow entity beginning with the specified word(s). There must be one or more words in the entity appearing after the specified word(s).

You can perform any Basic index search (word, co-occurrence, or positional phrase) with a Semantic index. Attempting to perform a Semantic index search with a Basic index results in an SQLCODE -149 error.

Multiple search_items can be specified, separated by spaces. This is an implicit AND test. For example:

SELECT Narrative FROM Aviation.TestIFind WHERE %ID %FIND 
search_index(NarrSemanticIdx,'<{plug electrode} (flight plan) instruct*',0,'en')
Copy code to clipboard

means that a Narrative text must include one or more iKnow entities that end with “plug electrode”, AND the literal phrase “flight plan”, AND the word “instruct” with a wildcard suffix, allowing for “instructor”, “instructors”, “instruction”, “instructed”, etc. These items can appear in any order in the text.

Validating a search-items String

You can use the %iFind.Utils.TestSearchString() method to validate a search_items string. This method enables you to detect syntax errors and ambiguous use of logical operators. For example, "word1 AND word2 OR word3" fails validation because it is logically ambiguous. Adding parentheses clarifies this string to either "word1 AND (word2 OR word3)" or "(word1 AND word2) OR word3". TestSearchString() returns 1 to indicate a valid search_items string.

The following example invokes this iFind utility as an SQL function:

SELECT %iFind.TestSearchString('orange AND (lemon OR lime)')
Copy code to clipboard

TestSearchString() returns a %Status value: A valid search_items string returns a status of 1. An invalid search_items string returns an object expression that begins with 0, followed by encoded error information.

Fuzzy Search

iFind supports fuzzy search to match records containing elements (words or entities) that “almost” match the search string. Fuzzy search can be used to account for small variations in writing (color vs. colour), misspellings (collor vs color), and different grammatical forms (color vs. colors).

iFind evaluates fuzzy matches by comparing the Levenshtein distance between the two words. The Levenshtein distance is the minimum number of single-character edits (insertions, deletions or substitutions) required to change one word into the other. The maximum number of single-character edits required is know as the maximum edit distance. The iFind maximum edit distance defaults to 2 characters. The maximum edit distance is separately applied to each element in the search string. For Basic iFind index, it is applied to each word in the search string. For Semantic iFind index, it is applied to each iKnow entity in the search string. (The examples that follow assume a Basic iFind index.)

For example, the phrase “analyse programme behaviour” is a fuzzy search match for “analyze program behavior” when maximum edit distance=2, because each word in the search string differs by an edit distance of (at most) 2 characters: analyse=analyze (1 substitution), programme=program (2 deletions), behaviour=behavior (1 deletion).

A word with that is lesser than or equal to the maximum edit distance is a fuzzy search match for any word with an equal or lesser number of characters. For example, if the edit distance is 2, the word “ab” would match any two-letter word (2 substitutions), any one-letter word (1 substitution, 1 deletion), any three-letter word containing either “a” or “b” (1 substitution, 1 insertion), and any four-letter word containing both “a” and “b” in that order (2 insertions).

  • Fuzzy search is supported on all iFind index types: Basic, Semantic, and Analytic. On a Basic index it performs fuzzy search on individual words. On a Semantic index it performs fuzzy search on individual iKnow entities.

  • Fuzzy search cannot be combined with wildcard search.

To specify fuzzy search for search_index() specify search_option as 3 for fuzzy search with the default edit distance of 2, or 3:n for fuzzy search with an edit distance specified as n characters. For example, setting 3:1 sets the edit distance=1, which in English is appropriate for matching most (but not all) singular and plural words. Setting 3:0 sets the edit distance=0, which is the same as iFind search without fuzzy search.

To specify fuzzy search for iFind methods, set the pSearchOption = $$$IFSEARCHFUZZY.

Stemming and Decompounding

Basic index, Semantic index, and Analytic index can all support stemming and decompounding. Stemming and decompounding are word-based, not iKnow entity-based operations. To enable an index for stem-aware searches, specify INDEXOPTION=1; to enable both stem-aware searches and decompounding-aware searches, specify INDEXOPTION=2.

Stemming

Stemming identifies the Stem Form of each word. The stem form unifies multiple grammatical forms of the same word. When using searchOption=1 at query time, iFind performs search and match operations using the Stem Form of a word, rather than the actual text form. By using searchOption=0, you can use the same index for regular (non-stemmed) searches.

Decompounding

Decompounding divides up compound words into their constituent words. iFind always combines decompounding with stemming; once a word is divided into its constituent parts, each of these parts is automatically stemmed. When using a decompounding search (searchOption=2), iFind compares the decompounding stems of the search term with the decompounded stems of the words in the indexed text field. iFind matches a decompounded word only when the stems of any of its constituent words match all constituent words of the search term.

For example, the search terms “thunder”, “storm”, or “storms” would all match the word “thunderstorms”. However, the search term “thunderstorms” would not match the word “thunder”, because its other constituent word (“storm”) is not matched.

The iFind decompounding algorithm using a language-specific dictionary that identifies possible constituent words. This dictionary should be populated through the %iKnow.Stemming.DecompoundingUtils class. For example, by pointing it to a text column prior to indexing. You may also wish to exempt specific words from decompounding. You can exempt individual words, character sequences, and training data word lists from decompounding using %iKnow.Stemming.DecompoundUtils.

Languages Not Supported by the iKnow Engine

You can use iFind Basic indices to index and search texts in languages for which there is no corresponding iKnow language model.

Because stemming is not dependent on iKnow semantic indexing, you can also perform Basic index word searches on stem forms of words, if a stemmer is available. You must specify INDEXOPTION=1 or INDEXOPTION=2 to perform stem searches. For example, Italian is not an iKnow supported language, but Caché provides a %Text stemmer for Italian.

The following limitations and caveats apply to iFind searching for languages not supported by iKnow:

  • An iKnow license is required to use this feature.

  • The language must separate words using spaces. Languages that do not uses word separators cannot be searched. However, Japanese (which does not uses word separators) can be searched because iKnow provides a Japanese language model.

  • Apostrophes do not separate words. iKnow recognizes contractions (such as “can’t”) and abbreviated verb forms (such as “there’s”) and separates them into two words, while ignoring apostrophes used for other purposes, such as possession (“John’s”). Without iKnow support, iFind cannot separate contractions and abbreviations into separate words. You can compensate for this by pre-processing your text, inserting a blank space before or after apostrophes as needed.

  • A UserDictionary cannot be applied to the texts before iFind indexing.

For further details, refer to Queries Invoking Free-text Search in the “Querying the Database” chapter of Using InterSystems SQL.

Highlighting

You can highlight words in a returned text using the search_items syntax. Highlighting syntax is:

(text,search_items,search_option)

search_items: Highlighting uses the same search_items syntax as searching. This allows you to use the same search_items value for both returning records and highlighting the strings within those records that caused them to be returned. This also allows you to use the TestSearchString() method to validate highlighting search_items syntax. However, because highlighting is applied to every instance of every match, highlighting ignores the search_items syntax AND, OR, and NOT logical operators in a search_items string.

search_option: The optional search_option is 0 (the default).

You can apply highlighting using either of the following:

  • SELECT item highlighting:

    SELECT %iFind.Highlight(Narrative,'"visibility [1-4] mile*" AND "temp* ? degrees"') 
    FROM Aviation.TestSQLSrch 
    WHERE %ID %FIND search_index(NarrBasicIdx,'"visibility [1-4] mile*" AND "temp* ? degrees"',0,'en')
    Copy code to clipboard
  • Utility method highlighting:

    You can use the %iFind.Utils.Highlight() method to perform an iFind Search and apply highlighting to the results.

By default, highlighting inserts the <b> and </b> (bold) XML tags at the appropriate places in the string. By default, highlighting is not case sensitive.

When used with Word Search, this method highlights separately each occurrence of each specified word.

When used with Positional Phrase Search, this method highlights each occurrence of the positional phrase.

iFind Examples

In the following examples, Basic index iFind syntax can be used with any type of iFind index. Semantic index iFind syntax requires a Semantic or Analytic iFind index.

These examples require that you have created and populated the Aviation.TestIFind table, as described in Indexing Sources for iFind Search earlier in this chapter.

For simplicity of display, these examples return record counts rather than the record text itself. These counts are the number of records that match the search criteria, not the number of matches found in the records. A record may contain multiple matches, but is only counted once.

Basic Search Examples

The following examples uses Basic index search to search the Aviation.TestSQLSrch table.

Search for records that contain at least one instance of the words “electrode”, “plug”, and “spark” (in any order):

SELECT COUNT(Narrative) FROM Aviation.TestSQLSrch 
WHERE %ID %FIND search_index(NarrBasicIdx,'electrode plug spark',0)
Copy code to clipboard

Note that this is word search, not string search. Therefore, the following example may return different results, and may actually return more results than the previous example:

SELECT COUNT(Narrative) FROM Aviation.TestSQLSrch 
WHERE %ID %FIND search_index(NarrBasicIdx,'electrodes plug spark',0)
Copy code to clipboard

Search for records that contain at least one instance of a word beginning with “electrode” (electrode, electrodes), and the word phrase “spark plug” (in any order):

SELECT COUNT(Narrative) FROM Aviation.TestSQLSrch 
WHERE %ID %FIND search_index(NarrBasicIdx,'electrode* "spark plug"',0)
Copy code to clipboard

Search for records that contain a word beginning with “electrode” (electrode, electrodes), and the word phrase “spark plug” (in any order) within a co-occurrence proximity window of 6 words. Note the punctuation used to specify words and word phrases in a co-occurrence search:

SELECT COUNT(Narrative) FROM Aviation.TestSQLSrch 
WHERE %ID %FIND search_index(NarrBasicIdx,'[electrode*,spark plug,1-6]',0)
Copy code to clipboard

Search for records that contain the two different word phrases normal wear and "normal" wear:

SELECT COUNT(Narrative) FROM Aviation.TestSQLSrch 
WHERE %ID %FIND search_index(NarrBasicIdx,'"normal wear"',0)
Copy code to clipboard
SELECT COUNT(Narrative) FROM Aviation.TestSQLSrch 
WHERE %ID %FIND search_index(NarrBasicIdx,'"\"normal\" wear"',0)
Copy code to clipboard

Search for records that contain at least one word containing the string seal (seal, seals, unseal, sealant, sealed, previously-sealed), and the word phrase “spark plug”:

SELECT COUNT(Narrative) FROM Aviation.TestSQLSrch 
WHERE %ID %FIND search_index(NarrBasicIdx,'*seal* "spark plug"',0)
Copy code to clipboard

Search for records that contain the wildcard phrase “wind from ? ? at ? knots.” Possible values might include “wind from the south at 25 knots” and “wind from 300 degrees at ten knots.” Note that if there is a space between two sequential question marks (? ?) the wildcard represents exactly two words; if there is no space between the two question marks (??) the wildcard represents from 0 to 6 words:

SELECT COUNT(Narrative) FROM Aviation.TestSQLSrch 
WHERE %ID %FIND search_index(NarrBasicIdx,'"wind from ? ? at ? knots"',0)
Copy code to clipboard

The following example uses Basic index with Regular Expression search (with n=4). It searches records that contain occurrences of strings specifying dates between “January 10” and “January 29” inclusive:

SELECT COUNT(Narrative) FROM Aviation.TestSQLSrch 
WHERE %ID %FIND search_index(NarrBasicIdx,'"January [1-2][0-9]"',4)
Copy code to clipboard

For further details, refer to Regular Expressions in Using ObjectScript.

Semantic Search Examples

The following examples use Semantic index iFind search to search the Aviation.TestIFind table.

Search for records that contain the iKnow entity “spark plug electrodes”:

SELECT COUNT(Narrative) FROM Aviation.TestIFind 
WHERE %ID %FIND search_index(NarrSemanticIdx,'{spark plug electrodes}',0)
Copy code to clipboard

Search for records that contain an iKnow entity ending with “spark plug” or “spark plugs”:

SELECT COUNT(Narrative) FROM Aviation.TestIFind 
WHERE %ID %FIND search_index(NarrSemanticIdx,'<{spark plug*}',0)
Copy code to clipboard

Search for records that contain both an iKnow entity ending with “spark plugs” and the iKnow entity “spark plugs”:

SELECT COUNT(Narrative) FROM Aviation.TestIFind 
WHERE %ID %FIND search_index(NarrSemanticIdx,'<{spark plugs} {spark plugs}',0)
Copy code to clipboard