Search Component

Properties   Methods   Events   Config Settings   Errors  

The Search component provides a simple way to search for documents in search indexes.

Syntax

nsoftware.IPWorksSearch.Search

Remarks

The Search component provides a simple way to search for documents in Lucene 4.8 search indexes. The component supports different types of search operations, including basic searches and boolean query construction. The component also provides control over query text processing via various query and analyzer types.

Loading the Search Index

The first step in using the component is to load the index that will be searched. Set IndexPath to the desired value and call OpenIndex to load the index. component.IndexPath = "PATH\\TO\\INDEX"; component.OpenIndex();

It is important to note that any external changes made to the index after it is loaded are not visible to the component until the OpenIndex method is called again. The method can be called as many times as needed to reload the index and reflect its latest changes in subsequent search operations. For example:

component.OpenIndex(); // Load the search index // ... Perform operations on the index ... component.OpenIndex(); // Reload the index to reflect any new updates

Simple Search

To begin a search operation, call the DoSimpleSearch method. This will prompt the component to find any documents in the index with fields that match the specified search query. The FieldName parameter is the name of the document field to look for, and QueryText is the text to look for in that field. This value fully supports the Lucene 4.8 query parser syntax, as defined in the Lucene query parser documentation.

// Search the index for a document with a field named "content" that has text matching the expression "Getting started" search.DoSimpleSearch("content", "Getting started");

Retrieving Search Results

After the calling the DoSimpleSearch method, the SearchResult event will fire for each document in the index that matches the search query. Within this event, ResultFields and GetResultField can be used to get information about each field in these documents. search.OnSearchResult += (s, e) => { foreach (ResultField field in search.ResultFields) { // Display the name and text content of every field in the current search result Console.WriteLine(field.Name + ": " + field.Text); } };

Highlighting Relevant Terms

The Highlight method can be called from within the SearchResult event to retrieve the most relevant text snippet of a field from a search result. The most relevant terms within this snippet will be highlighted using the HTML tag specified in the HighlightTag property. search.HighlightTag = "<em>"; // Tell the component we want to highlight each relevant term with <em> tags search.OnSearchResult += (s, e) => { // If the current search result has a field named "content" with // a value of "Getting started with IPWorksSearch", this method will return // "<em>Getting started</em> with IPWorksSearch" search.HighlightField("content"); };

Pagination

The component handles pagination automatically. After performing a search operation with DoSimpleSearch or DoSearch, the HasMorePages property will indicate whether more pages of results are available. A subsequent call to the same method will retrieve the next page of results if HasMorePages is true. // Search the index until there are no more pages left do { component.DoSearch(); } while (search.HasMorePages);

Boolean Queries

For more complex search operations, the component supports boolean queries. These queries provide more direct control over search operations and enable searching for documents that must match multiple criteria.

Creating Boolean Queries

To begin a boolean search, call AddQuery to add queries to the Queries collection. Each query specifies the field to search, the value to look for, the type of content to look for, and how the query relates to other queries. For more information on the different supported query types please see the documentation for the QueryType field.

// Add a term query to search for documents containing "nsoftware" in the "company" field component.AddQuery("company", "nsoftware", (int)TQueryTypes.qtTerm, (int)TOccurTypes.otMust); // Add a phrase query to search for documents containing the phrase "software development" in the "content" field component.AddQuery("content", "software development", (int)TQueryTypes.qtPhrase, (int)TOccurTypes.otMust);

After populating the Queries collection with search queries, call the DoSearch method to start the boolean search operation. This will combine all of the queries added to the Queries collection based on their occur types. The SearchResult event will then fire for each document in the index that matches the combined queries. For more information on how these queries are combined, please see the documentation for the OccurType field. component.DoSearch();

Unloading the Index

Once the search operations are complete, the index can be unloaded by calling the CloseIndex method. component.CloseIndex();

Property List


The following is the full list of the properties of the component with short descriptions. Click on the links for further details.

AnalyzerThe analyzer used in search operations.
HasMorePagesWhether or not more pages of results are available for the ongoing search operation.
HighlightTagThe HTML tag used to highlight the most relevant terms in a highlighted field.
IndexPathThe path to the search index.
PageSizeThe maximum number of documents that can be retrieved per each page of search results.
QueriesA collection of queries that determine the criteria for finding documents in the search index.
ResultCountThe total number of search results returned after a search is performed.
ResultFieldsThe fields of the current search result document.

Method List


The following is the full list of the methods of the component with short descriptions. Click on the links for further details.

AddQueryCreates a search query.
CloseIndexUnloads the search index.
ConfigSets or retrieves a configuration setting.
DoSearchSearches the index for documents that match one or more queries.
DoSimpleSearchSearches the index for documents that match a single search query.
GetResultFieldRetrieves the text value of a field from the current search result.
HighlightRetrieves the most relevant text snippet of a field from the current search result.
OpenIndexLoads the search index.

Event List


The following is the full list of the events fired by the component with short descriptions. Click on the links for further details.

ErrorFires to provide information about errors during search operations.
LogThis event fires once for each log message.
SearchResultFires for each document returned from a search operation.

Config Settings


The following is a list of config settings for the component with short descriptions. Click on the links for further details.

FuzzyMaxEditsThe tolerance level for term variations in a fuzzy search.
HighlightFieldIndexThe index of a multi-valued field to highlight in the current search result document.
LogLevelThe level of detail that is logged through the Log event.
PhraseSlopThe maximum number of positions by which terms in a phrase query can shift to qualify as a match for a document.
BuildInfoInformation about the product's build.
GUIAvailableWhether or not a message loop is available for processing events.
LicenseInfoInformation about the current license.
MaskSensitiveDataWhether sensitive data is masked in log messages.
UseFIPSCompliantAPITells the component whether or not to use FIPS certified APIs.
UseInternalSecurityAPIWhether or not to use the system security libraries or an internal implementation.

Analyzer Property (Search Component)

The analyzer used in search operations.

Syntax

public SearchAnalyzers Analyzer { get; set; }

enum SearchAnalyzers { atStandard, atStop, atWhitespace, atSimple, atEmail }
Public Property Analyzer As SearchAnalyzers

Enum SearchAnalyzers atStandard atStop atWhitespace atSimple atEmail End Enum

Default Value

1

Remarks

Specifies the analyzer used in search operations.

Possible values are:

0 (atNone) Does not correspond to any analyzer.
1 (atStandard)The most commonly used analyzer. Breaks down text into tokens based on the Unicode Text Segmentation algorithm, as specified in Unicode Standard Annex #29. Removes stop words and changes all letters to lowercase. Does not recognize URLs or emails. For example, the text This is a SAMPLE sentence. support@nsoftware.com https://www.nsoftware.com 1234 will be broken down into the following list of tokens: sample, sentence, support, nsoftware.com, https, www.nsoftware.com, 1234.
2 (atStop) The same as atSimple, but this analyzer removes stop words. For example, the text This is a SAMPLE sentence. support@nsoftware.com https://www.nsoftware.com 1234 will be broken down into the following list of tokens: sample, sentence, support, nsoftware, com, https, www, nsoftware, com.
3 (atWhitespace) Breaks down text into tokens whenever it encounters a whitespace character without applying any further processing to the input text. For example, the text This is a SAMPLE sentence. support@nsoftware.com https://www.nsoftware.com 1234 will be broken down into the following list of tokens: This, is, a, SAMPLE, sentence., support@nsoftware.com, https://www.nsoftware.com, 1234.
4 (atSimple) Breaks down text into tokens based on anything that is not a letter. This analyzer completely discards non-letter characters and changes all letters to lowercase. For example, the text This is a SAMPLE sentence. support@nsoftware.com https://www.nsoftware.com 1234 will be broken down into the following list of tokens: this, is, a, sample, sentence, support, nsoftware, com, https, www, nsoftware, com.
5 (atEmail) The same as atStandard, but this analyzer recognizes URLs and emails. For example, the text This is a SAMPLE sentence. support@nsoftware.com https://www.nsoftware.com 1234 will be broken down into the following list of tokens: sample, sentence, support@nsoftware.com, https://www.nsoftware.com, 1234.

Analyzers and Tokenization

Before text is stored in a search index, it goes through an analyzer that breaks the text down into smaller, searchable parts known as tokens. The rules that determine how text is broken down into distinct tokens are defined by the analyzer type.

The way tokens are created directly affects the precision and relevance of search results. For example, if an analyzer does not break down the terms "WORD" and "word" as the same value, searches for one may not bring up results for the other.

Stop Words

Words that are omitted from text processing because of their lack of significant meaning are known as stop words. When the analyzer type is set to atStandard, atStop, or atEmail, stop words will be completely ignored by the analyzer in to improve search performance and relevance.

The full list of stop words that are ignored by these analyzers can be found below:

a, an, and, are, as, at, be, but, by, for, if, in, into, is, it, no, not, of, on,
or, such, that, the, their, then, there, these, they, this, to, was, will, with

Resetting Pagination

The component will automatically reset its pagination state if the OpenIndex method is called or if there are changes to Queries, Analyzer, IndexPath, ResultFields, or PageSize. When this happens, the next call to DoSearch or DoSimpleSearch will start over from the first page of results.

Example: // Search through every page of results do { component.DoSearch(); } while (component.HasMorePages); // Call OpenIndex(), or make changes to the Queries, AnalyzerType, IndexPath, ResultFields, or PageSize properties component.OpenIndex(); // After that, the current search operation will cease and automatically start over // from the first page of results the next time DoSearch() or DoSimpleSearch() is called component.DoSearch();

This property is not available at design time.

HasMorePages Property (Search Component)

Whether or not more pages of results are available for the ongoing search operation.

Syntax

public bool HasMorePages { get; }
Public ReadOnly Property HasMorePages As Boolean

Default Value

False

Remarks

Indicates whether or not more pages of results are available for the ongoing search operation.

Pagination

When DoSearch is called, the component will retrieve a single page of search results. If additional results are available, HasMorePages will be automatically set to true. Subsequent calls to DoSearch will then retrieve the next page of results, if one is available.

The example below retrieves all of the search results that match the queries in the Queries collection.

Example: // Search through every page of results do { search.DoSearch(); } while (search.HasMorePages);

This property is read-only.

HighlightTag Property (Search Component)

The HTML tag used to highlight the most relevant terms in a highlighted field.

Syntax

public string HighlightTag { get; set; }
Public Property HighlightTag As String

Default Value

"<b>"

Remarks

Specifies the HTML tag used to highlight the most relevant terms in the value returned by the Highlight method.

Highlighting Relevant Terms

When the Highlight method is called, the most relevant terms in the text snippet that it returns will be highlighted with the HTML tag specified in the HighlightTag property.

For example, if HighlightTag is set to <em> and a search operation for the word "sample" is performed, the output of the method might look like this: This is a <em>sample</em> sentence.

Example: // Assuming we only have a single term query with a value of "sample" search.HighlightTag = "<em>"; // Tell the component we want to highlight each relevant term with <em> tags search.OnSearchResult += (s, e) => { // If the current search result has a field named "content" with // a value of "This is a sample sentence", this method will return // the value "This is a <em>sample</em> sentence." search.HighlightField("content"); };

IndexPath Property (Search Component)

The path to the search index.

Syntax

public string IndexPath { get; set; }
Public Property IndexPath As String

Default Value

""

Remarks

The filesystem path to the Lucene search index that will be searched. This property must be specified before calling the OpenIndex method.

Loading a Search Index

If the specified path contains a pre-existing search index, it will be loaded by the component when OpenIndex is called. The DoSearch method can then be called while the index is loaded to perform search operations and retrieve documents from the index.

Example: component.IndexPath = "PATH\\TO\\INDEX"; // Specify the path to the search index component.OpenIndex(); // Load the index // ... Perform operations on the index ... component.CloseIndex();

Relative and Absolute Paths

If the path value begins with a / or a drive letter such as D:/, it is considered an absolute path. The component will interpet any other value as a relative path to resolve in relation to the current directory.

Resetting Pagination

The component will automatically reset its pagination state if the OpenIndex method is called or if there are changes to Queries, Analyzer, IndexPath, ResultFields, or PageSize. When this happens, the next call to DoSearch or DoSimpleSearch will start over from the first page of results.

Example: // Search through every page of results do { component.DoSearch(); } while (component.HasMorePages); // Call OpenIndex(), or make changes to the Queries, AnalyzerType, IndexPath, ResultFields, or PageSize properties component.OpenIndex(); // After that, the current search operation will cease and automatically start over // from the first page of results the next time DoSearch() or DoSimpleSearch() is called component.DoSearch();

PageSize Property (Search Component)

The maximum number of documents that can be retrieved per each page of search results.

Syntax

public int PageSize { get; set; }
Public Property PageSize As Integer

Default Value

20

Remarks

Specifies the maximum number of documents that can be retrieved per each page of search results. This value can be used to control the maximum number of results that will be returned after calling DoSearch.

Example: // Tell the component to return at most 5 documents per each page of results component.PageSize = 5; // Search through every page of results do { // The "SearchResult" event will fire at most 5 times every time DoSearch is called component.DoSearch(); } while (component.HasMorePages);

Resetting Pagination

The component will automatically reset its pagination state if the OpenIndex method is called or if there are changes to Queries, Analyzer, IndexPath, ResultFields, or PageSize. When this happens, the next call to DoSearch or DoSimpleSearch will start over from the first page of results.

Example: // Search through every page of results do { component.DoSearch(); } while (component.HasMorePages); // Call OpenIndex(), or make changes to the Queries, AnalyzerType, IndexPath, ResultFields, or PageSize properties component.OpenIndex(); // After that, the current search operation will cease and automatically start over // from the first page of results the next time DoSearch() or DoSimpleSearch() is called component.DoSearch();

Queries Property (Search Component)

A collection of queries that determine the criteria for finding documents in the search index.

Syntax

public QueryList Queries { get; }
Public Property Queries As QueryList

Remarks

Contains a collection of queries that determine the search criteria for finding documents in the search index. A query can be added by accessing this property directly, or by calling the AddQuery method.

Adding Queries

When DoSearch is called, the queries in the collection are combined to search the index and the SearchResult event will fire for each document that matches the combined queries.

Example (Simple): // Look for text that matches "Sample query text" in a document field named "content" component.AddQuery("content", "Sample query text", (int)TQueryTypes.qtParsed, (int)TOccurTypes.otMust); // This will return documents with fields that match the query. // Results will be accessible via the SearchResult event. component.DoSearch();

Example (Advanced): // Look for text that matches "Sample query text" in a document field with the name "content" // The "otMust" occur type indicates that this criteria must be met for the document to appear in the results component.AddQuery("content", "Sample query text", (int)TQueryTypes.qtParsed, (int)TOccurTypes.otMust); // Look for text that starts with "IP" in a document field with the name "toolkit" component.AddQuery("toolkit", "IP", (int)TQueryTypes.qtPrefix, (int)TOccurTypes.otMust); // This will return documents with fields that match both queries. // Results will be accessible via the SearchResult event. component.DoSearch();

Resetting Pagination

The component will automatically reset its pagination state if the OpenIndex method is called or if there are changes to Queries, Analyzer, IndexPath, ResultFields, or PageSize. When this happens, the next call to DoSearch or DoSimpleSearch will start over from the first page of results.

Example: // Search through every page of results do { component.DoSearch(); } while (component.HasMorePages); // Call OpenIndex(), or make changes to the Queries, AnalyzerType, IndexPath, ResultFields, or PageSize properties component.OpenIndex(); // After that, the current search operation will cease and automatically start over // from the first page of results the next time DoSearch() or DoSimpleSearch() is called component.DoSearch();

This property is not available at design time.

Please refer to the Query type for a complete list of fields.

ResultCount Property (Search Component)

The total number of search results returned after a search is performed.

Syntax

public int ResultCount { get; }
Public ReadOnly Property ResultCount As Integer

Default Value

0

Remarks

Contains the total number of search results returned after a search operation is performed. When DoSearch is called to search the index, this property is automatically set to the total number of documents that match the search Queries.

The maximum number of documents that can be returned can be controlled with the PageSize property.

This property is read-only.

ResultFields Property (Search Component)

The fields of the current search result document.

Syntax

public ResultFieldList ResultFields { get; }
Public Property ResultFields As ResultFieldList

Remarks

Contains the fields of the current search result document.

Retrieving Search Results

When DoSearch or DoSimpleSearch is called, the SearchResult event will fire for each document in the index that matches the search queries. When the event fires, the ResultFields collection will be automatically populated by the component to provide information about every field in the current search result document. The example below demonstrates how to retrieve these fields and display their text contents.

Example: search.OnSearchResult += (s, e) => { foreach (ResultField field in search.ResultFields) { // Display the name and text content of every field Console.WriteLine(field.Name + ": " + field.Text); } };

Alternatively, the GetResultField method can be used inside the event to retrieve the text value of a known field from the current search result.

Example: search.OnSearchResult += (s, e) => { // Display a specific field value string authorFieldValue = search.GetResultField("author"); Console.WriteLine("author: " + authorFieldValue); };

Resetting Pagination

The component will automatically reset its pagination state if the OpenIndex method is called or if there are changes to Queries, Analyzer, IndexPath, ResultFields, or PageSize. When this happens, the next call to DoSearch or DoSimpleSearch will start over from the first page of results.

Example: // Search through every page of results do { component.DoSearch(); } while (component.HasMorePages); // Call OpenIndex(), or make changes to the Queries, AnalyzerType, IndexPath, ResultFields, or PageSize properties component.OpenIndex(); // After that, the current search operation will cease and automatically start over // from the first page of results the next time DoSearch() or DoSimpleSearch() is called component.DoSearch();

Please refer to the ResultField type for a complete list of fields.

AddQuery Method (Search Component)

Creates a search query.

Syntax

public void AddQuery(string field, string value, int queryType, int occurType);
Public Sub AddQuery(ByVal field As String, ByVal value As String, ByVal queryType As Integer, ByVal OccurType As Integer)

Remarks

Creates a search query and adds it to the Queries collection.

When DoSearch is called, the added queries are combined to search the index and the SearchResult event will fire for each document that matches the combined queries.

Field specifies the exact name of the document field to be searched.

Value specifies the text content to look for in the specified document field. Its format depends on the value passed into the QueryType parameter.

QueryType defines the type of search query that will be performed. Its value determines how the Field and Value parameters are used to identify matching documents.

0 (qtTerm) Retrieves documents that contain an exact word or token. The query Value should be set to a single word or term, such as apple or machine learning.
1 (qtPhrase) Retrieves documents that contain a single phrase. The query Value should be set to a single phrase, such as This is a single phrase. This query type preserves the order of words within the specified phrase.
2 (qtPrefix) Retrieves documents with terms that start with the prefix specified in the query Value. For example, a query value equal to IP would match with documents that contain IPWorks, IPConfig, or IPInfo.
3 (qtFuzzy) Similar to qtTermQuery, but this query type accounts for typos and minor variations of the query Value. For example, a query value of banana would match with documents that contain bananc.
4 (qtRegexp) Retrieves documents with terms that match a regular expression. The query Value should be set to a regular expression pattern, such as ^[a-z]{3,5}$.
5 (qtTermRange) Retrieves documents that contain terms that fall within an alphabetical range. The query Value should be set to an alphanumeric range in the following format: min - max. For instance: This range is always inclusive.
6 (qtNumericRangeQuery) Retrieves documents that contain numerical data within a numeric range. The query Value should be set to a numeric range in the following format: min - max. For instance: 10 - 15. This range is always inclusive.
7 (qtMatchAllDocsQuery) Retrieves all of the documents in the index. This query type ignores the query Field and Value altogether.
8 (qtParsedQuery) Retrieves documents based on a Lucene query expression. The query Value can be a human-readable search query that makes use of the Lucene 4.8 query parser syntax, as defined in the Lucene query parser documentation. In most cases, this query type is normally used for searching the index based on user input.

OccurType determines how queries relate to each other when they are combined. Possible values are:

0 (OCCUR_MUST) Only include documents that match the query in the search results. If multiple queries with this occur type exist, a document must match all of them in order to be included in the search results.
1 (OCCUR_SHOULD) Documents that do not match the query may appear in search results, but the ones that do will be prioritized and have a higher relevance score.
2 (OCCUR_MUST_NOT) Exclude any documents that match the query from the search results. This can be used to filter out documents that contain specific content.

Example (Simple): // Look for text that matches "Sample query text" in a document field named "content" component.AddQuery("content", "Sample query text", (int)TQueryTypes.qtParsed, (int)TOccurTypes.otMust); // This will return documents with fields that match the query. // Results will be accessible via the SearchResult event. component.DoSearch();

Example (Advanced): // Look for text that matches "Sample query text" in a document field with the name "content" // The "otMust" occur type indicates that this criteria must be met for the document to appear in the results component.AddQuery("content", "Sample query text", (int)TQueryTypes.qtParsed, (int)TOccurTypes.otMust); // Look for text that starts with "IP" in a document field with the name "toolkit" component.AddQuery("toolkit", "IP", (int)TQueryTypes.qtPrefix, (int)TOccurTypes.otMust); // This will return documents with fields that match both queries. // Results will be accessible via the SearchResult event. component.DoSearch();

Parsed Query Notes

When DoSearch is called, the query Value for qtParsed queries is automatically broken down and processed with an analyzer. The Analyzer property can be used to control how this text is transformed into more searchable terms.

Example: component.AnalyzerType = (int)TSearchAnalyzerTypes.atWhitespace; // the Whitespace analyzer keeps stop words and uppercase characters // This query value will be broken down into the following list of term queries: "This, is, a, SAMPLE, query" component.AddQuery("data", "This is a SAMPLE query", (int)TQueryTypes.qtParsed, (int)TOccurTypes.otMust); component.AnalyzerType = (int)TSearchAnalyzerTypes.atWhitespace; // the Standard analyzer converts all letters to lowercase and removes stop words // This query value will be broken down into the following list of term queries: "this, sample, query" component.AddQuery("data", "This is a SAMPLE query", (int)TQueryTypes.qtParsed, (int)TOccurTypes.otMust);

Numeric Range Query Notes

When creating qtNumericRange queries, the field types that will be targeted by the query can be specified by appending a specific character to one of the boundary values in the range.

If both of the values in the range are integers numbers without a suffix, the the range query will exclusively target Int32 fields. To include Int64 fields instead, the l or L characters can be appended to one of the integer values specified in the query Value.

Example: // Range query over a range of integer values // Since both of the values in the range are integers without special syntax, the component will only // look for Int32 fields that match this query component.AddQuery("data", "5 - 10", (int)TQueryTypes.qtNumericRange, (int)TOccurTypes.otMust); // Range query over a range of long values // To include Int64 fields in the search results, an 'l' or 'L' must be appended to one of the bound values // in the specified range component.AddQuery("data", "2000 - 192039l", (int)TQueryTypes.qtNumericRange, (int)TOccurTypes.otMust);

If a decimal is present without any suffix, the range query will ignore Float fields and target Double fields. To target Float fields instead, the f or F characters can be appended to one of the floating-point values specified in the query Value.

Example: // Range query over a range of double values // If a decimal is present without any suffix, the query will only target double fields component.AddQuery("data", "3 - 4.14592", (int)TQueryTypes.qtNumericRange, (int)TOccurTypes.otMust); // Range query over a range of float values // Adding a 'f' or 'F' character next to a floating point number will make the query applicable to float fields component.AddQuery("data", "5.13f - 10", (int)TQueryTypes.qtNumericRange, (int)TOccurTypes.otMust);

Term Range Query Notes

When creating qtTermRange queries, the - and \ characters cannot be included in the boundary values specified in the range by default. To include these, they must be escaped by appending a \ character in front of each.

Example: // Term range query over a range of dates // Since hyphens are part of the date format, they need to be escaped. // This query specifies a range from "5-7-2024" to "5-8-2024" component.AddQuery("data", "5\\-7\\-2024 - 5\\-8\\-2024", (int)TQueryTypes.qtTermRange, (int)TOccurTypes.otMust);

CloseIndex Method (Search Component)

Unloads the search index.

Syntax

public void CloseIndex();
Public Sub CloseIndex()

Remarks

Unloads the search index.

Config Method (Search Component)

Sets or retrieves a configuration setting.

Syntax

public string Config(string configurationString);
Public Function Config(ByVal ConfigurationString As String) As String

Remarks

Config is a generic method available in every component. It is used to set and retrieve configuration settings for the component.

These settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the component, access to these internal properties is provided through the Config method.

To set a configuration setting named PROPERTY, you must call Config("PROPERTY=VALUE"), where VALUE is the value of the setting expressed as a string. For boolean values, use the strings "True", "False", "0", "1", "Yes", or "No" (case does not matter).

To read (query) the value of a configuration setting, you must call Config("PROPERTY"). The value will be returned as a string.

DoSearch Method (Search Component)

Searches the index for documents that match one or more queries.

Syntax

public void DoSearch();
Public Sub DoSearch()

Remarks

Searches the index for any documents that match the queries specified in the Queries collection.

Note: This method does not clear the contents of the Queries collection.

Retrieving Search Results

When DoSearch or DoSimpleSearch is called, the SearchResult event will fire for each document in the index that matches the search queries. When the event fires, the ResultFields collection will be automatically populated by the component to provide information about every field in the current search result document. The example below demonstrates how to retrieve these fields and display their text contents.

Example: search.OnSearchResult += (s, e) => { foreach (ResultField field in search.ResultFields) { // Display the name and text content of every field Console.WriteLine(field.Name + ": " + field.Text); } };

Alternatively, the GetResultField method can be used inside the event to retrieve the text value of a known field from the current search result.

Example: search.OnSearchResult += (s, e) => { // Display a specific field value string authorFieldValue = search.GetResultField("author"); Console.WriteLine("author: " + authorFieldValue); };

Pagination

This method retrieves a single page of search results. If additional results are available, HasMorePages will be automatically set to true. Subsequent calls to this method will then retrieve the next page of results, if one is available.

The example below retrieves all of the search results that match the queries in the Queries collection.

Example: // Search through every page of results do { search.DoSearch(); } while (search.HasMorePages);

Resetting Pagination

The component will automatically reset its pagination state if the OpenIndex method is called or if there are changes to Queries, Analyzer, IndexPath, ResultFields, or PageSize. When this happens, the next call to DoSearch or DoSimpleSearch will start over from the first page of results.

Example: // Search through every page of results do { component.DoSearch(); } while (component.HasMorePages); // Call OpenIndex(), or make changes to the Queries, AnalyzerType, IndexPath, ResultFields, or PageSize properties component.OpenIndex(); // After that, the current search operation will cease and automatically start over // from the first page of results the next time DoSearch() or DoSimpleSearch() is called component.DoSearch();

DoSimpleSearch Method (Search Component)

Searches the index for documents that match a single search query.

Syntax

public void DoSimpleSearch(string fieldName, string queryText);
Public Sub DoSimpleSearch(ByVal FieldName As String, ByVal QueryText As String)

Remarks

Searches the index for documents that match a single search query. To search for documents that match multiple queries, use DoSearch instead.

FieldName specifies the exact name of the document field to be searched.

QueryText defines what to look for in the specified document field. Its value may be a human-readable search query that makes use of the Lucene 4.8 query syntax, as defined in the Lucene query parser documentation.

Example:

component.DoSimpleSearch();

Retrieving Search Results

When DoSearch or DoSimpleSearch is called, the SearchResult event will fire for each document in the index that matches the search queries. When the event fires, the ResultFields collection will be automatically populated by the component to provide information about every field in the current search result document. The example below demonstrates how to retrieve these fields and display their text contents.

Example: search.OnSearchResult += (s, e) => { foreach (ResultField field in search.ResultFields) { // Display the name and text content of every field Console.WriteLine(field.Name + ": " + field.Text); } };

Alternatively, the GetResultField method can be used inside the event to retrieve the text value of a known field from the current search result.

Example: search.OnSearchResult += (s, e) => { // Display a specific field value string authorFieldValue = search.GetResultField("author"); Console.WriteLine("author: " + authorFieldValue); };

Pagination

This method retrieves a single page of search results. If additional results are available, HasMorePages will be automatically set to true. Subsequent calls to this method will then retrieve the next page of results, if one is available.

The example below retrieves all of the search results that match the specified search query.

Example: // Search through every page of results do { search.DoSimpleSearch(); } while (search.HasMorePages);

GetResultField Method (Search Component)

Retrieves the text value of a field from the current search result.

Syntax

public string GetResultField(string fieldName);
Public Function GetResultField(ByVal fieldName As String) As String

Remarks

Retrieves the text value of a field from the current search result document during an ongoing search operation. This method should only be called within an event handler for the SearchResult event.

FieldName specifies the name of the document field for which the text value is retrieved.

Multi-Valued Fields

This method is intended for document fields with unique field names within the current search result document. For documents with multiple distinct fields that share the same name, it will only return the value of the first field in the document that matches the specified FieldName.

Additional values for multi-valued fields may be accessed through the ResultFields collection.

Example: // This should only be done within the SearchResult event for (ResultField field in search.ResultFields) { // Display the text value of each field in the current search result document // this includes fields that have the same name Console.WriteLine(field.Text); }

Highlight Method (Search Component)

Retrieves the most relevant text snippet of a field from the current search result.

Syntax

public string Highlight(string fieldName);
Public Function Highlight(ByVal fieldName As String) As String

Remarks

Retrieves the most relevant text snippet of a document field from the current search result document. This method should only be called within an event handler for the SearchResult event.

FieldName specifies the name of the document field for which the relevant text snippet will be retrieved. If the specified field does not contain any relevant terms, this method will return an empty string.

Highlighting Relevant Terms

When the Highlight method is called, the most relevant terms in the text snippet that it returns will be highlighted with the HTML tag specified in the HighlightTag property.

For example, if HighlightTag is set to <em> and a search operation for the word "sample" is performed, the output of the method might look like this: This is a <em>sample</em> sentence.

Example: // Assuming we only have a single term query with a value of "sample" search.HighlightTag = "<em>"; // Tell the component we want to highlight each relevant term with <em> tags search.OnSearchResult += (s, e) => { // If the current search result has a field named "content" with // a value of "This is a sample sentence", this method will return // the value "This is a <em>sample</em> sentence." search.HighlightField("content"); };

Multi-Valued Fields

If the current search result document contains multiple fields with a name equal to FieldName, this method will only return the most relevant text snippet of the first one in the document by default.

The HighlightFieldIndex configuration setting can be used to specify which occurrence to highlight among fields with the same name when multiple are present in the document. It takes in a zero-based index that identifies one of these similarly-named fields. This index value only applies to fields that match the FieldName parameter, and does not consider fields with different names.

Example: // Assuming the current result is a document with two separate fields that share the same name but have different values, like so: // { // author: "John Smith", // author: "Robert Roe" // } search.OnSearchResult += (s, e) => { search.Config("HighlightFieldIndex=1"); // Tell the component we want to retrieve the second field search.HighlightField("author"); // Returns the most relevant text snippet for the field with the value "Robert Roe" };

OpenIndex Method (Search Component)

Loads the search index.

Syntax

public void OpenIndex();
Public Sub OpenIndex()

Remarks

Loads the search index located in the path specified by IndexPath. This method should be called at least once before searching the index with DoSearch. To unload the search index, call CloseIndex instead.

Index Updates

When this method is called, the component will load a snapshot of the index at the time it was opened. Any external changes made to the index afterwards will not be reflected in subsequent search operations until this method is called again.

This method can be called multiple times to reload the index and reflect its latest changes in search operations. Example:

component.OpenIndex(); // Load the search index // ... Perform operations on the index ... component.OpenIndex(); // Reload the index to reflect any new updates

Resetting Pagination

The component will automatically reset its pagination state if the OpenIndex method is called or if there are changes to Queries, Analyzer, IndexPath, ResultFields, or PageSize. When this happens, the next call to DoSearch or DoSimpleSearch will start over from the first page of results.

Example: // Search through every page of results do { component.DoSearch(); } while (component.HasMorePages); // Call OpenIndex(), or make changes to the Queries, AnalyzerType, IndexPath, ResultFields, or PageSize properties component.OpenIndex(); // After that, the current search operation will cease and automatically start over // from the first page of results the next time DoSearch() or DoSimpleSearch() is called component.DoSearch();

Error Event (Search Component)

Fires to provide information about errors during search operations.

Syntax

public event OnErrorHandler OnError;

public delegate void OnErrorHandler(object sender, SearchErrorEventArgs e);

public class SearchErrorEventArgs : EventArgs {
  public int ErrorCode { get; }
  public string Description { get; }
}
Public Event OnError As OnErrorHandler

Public Delegate Sub OnErrorHandler(sender As Object, e As SearchErrorEventArgs)

Public Class SearchErrorEventArgs Inherits EventArgs
  Public ReadOnly Property ErrorCode As Integer
  Public ReadOnly Property Description As String
End Class

Remarks

Fires in case of exceptional conditions during search operations. Normally, the component will raise an exception instead.

ErrorCode contains an error code and Description contains a textual description of the error. For a list of valid error codes and their descriptions, please refer to the Error Codes section.

Log Event (Search Component)

This event fires once for each log message.

Syntax

public event OnLogHandler OnLog;

public delegate void OnLogHandler(object sender, SearchLogEventArgs e);

public class SearchLogEventArgs : EventArgs {
  public int LogLevel { get; }
  public string Message { get; }
  public string LogType { get; }
}
Public Event OnLog As OnLogHandler

Public Delegate Sub OnLogHandler(sender As Object, e As SearchLogEventArgs)

Public Class SearchLogEventArgs Inherits EventArgs
  Public ReadOnly Property LogLevel As Integer
  Public ReadOnly Property Message As String
  Public ReadOnly Property LogType As String
End Class

Remarks

This event fires once for each log message generated by the component. The verbosity is controlled by the LogLevel setting.

LogLevel indicates the level of detail of the log message. Possible values are:

0 (None - default) No events are logged.
1 (Info) Informational events are logged.
2 (Verbose) Detailed data are logged.
3 (Debug) Debug data are logged.

Message is the log entry.

LogType identifies the type of log entry.

SearchResult Event (Search Component)

Fires for each document returned from a search operation.

Syntax

public event OnSearchResultHandler OnSearchResult;

public delegate void OnSearchResultHandler(object sender, SearchSearchResultEventArgs e);

public class SearchSearchResultEventArgs : EventArgs {
  public string score { get; }
}
Public Event OnSearchResult As OnSearchResultHandler

Public Delegate Sub OnSearchResultHandler(sender As Object, e As SearchSearchResultEventArgs)

Public Class SearchSearchResultEventArgs Inherits EventArgs
  Public ReadOnly Property score As String
End Class

Remarks

Fires for each document that matches the search queries specified in the Queries collection when a search operation is performed with DoSearch.

Score represents how closely the current document matches the search queries for the ongoing search operation. Higher Score values indicate a more relevant match.

Retrieving Search Results

When DoSearch or DoSimpleSearch is called, the SearchResult event will fire for each document in the index that matches the search queries. When the event fires, the ResultFields collection will be automatically populated by the component to provide information about every field in the current search result document. The example below demonstrates how to retrieve these fields and display their text contents.

Example: search.OnSearchResult += (s, e) => { foreach (ResultField field in search.ResultFields) { // Display the name and text content of every field Console.WriteLine(field.Name + ": " + field.Text); } };

Alternatively, the GetResultField method can be used inside the event to retrieve the text value of a known field from the current search result.

Example: search.OnSearchResult += (s, e) => { // Display a specific field value string authorFieldValue = search.GetResultField("author"); Console.WriteLine("author: " + authorFieldValue); };

Query Type

Holds information about a search query.

Remarks

This is used to define the search criteria for finding documents in the search index.

The following fields are available:

Fields

Boost
string

Default: ""

The boost factor of the search query. Its value determines the importance of the query in relation to other search queries.

A value greater than 1 increases the final relevance score of any documents that match this query, making them more likely to appear at the top of search results. A value between 0 and 1 decreases the relevance score, making any documents that match this query appear lower in the search results.

A value of 1 has no effect on the query's final relevance score. By default, this field is set to 1.

FieldName
string

Default: ""

The name of the document field to be searched.

OccurType
TOccurTypes (read-only)

Default: 0

Controls how this query relates to other search queries when they are combined to search the index.

Possible values are:

0 (OCCUR_MUST) Only include documents that match the query in the search results. If multiple queries with this occur type exist, a document must match all of them in order to be included in the search results.
1 (OCCUR_SHOULD) Documents that do not match the query may appear in search results, but the ones that do will be prioritized and have a higher relevance score.
2 (OCCUR_MUST_NOT) Exclude any documents that match the query from the search results. This can be used to filter out documents that contain specific content.

QueryType
TQueryTypes (read-only)

Default: 0

The type of search query that will be performed. Its value determines how the Field and Value fields are used to identify matching documents.

0 (qtTerm) Retrieves documents that contain an exact word or token. The query Value should be set to a single word or term, such as apple or machine learning.
1 (qtPhrase) Retrieves documents that contain a single phrase. The query Value should be set to a single phrase, such as This is a single phrase. This query type preserves the order of words within the specified phrase.
2 (qtPrefix) Retrieves documents with terms that start with the prefix specified in the query Value. For example, a query value equal to IP would match with documents that contain IPWorks, IPConfig, or IPInfo.
3 (qtFuzzy) Similar to qtTermQuery, but this query type accounts for typos and minor variations of the query Value. For example, a query value of banana would match with documents that contain bananc.
4 (qtRegexp) Retrieves documents with terms that match a regular expression. The query Value should be set to a regular expression pattern, such as ^[a-z]{3,5}$.
5 (qtTermRange) Retrieves documents that contain terms that fall within an alphabetical range. The query Value should be set to an alphanumeric range in the following format: min - max. For instance: This range is always inclusive.
6 (qtNumericRangeQuery) Retrieves documents that contain numerical data within a numeric range. The query Value should be set to a numeric range in the following format: min - max. For instance: 10 - 15. This range is always inclusive.
7 (qtMatchAllDocsQuery) Retrieves all of the documents in the index. This query type ignores the query Field and Value altogether.
8 (qtParsedQuery) Retrieves documents based on a Lucene query expression. The query Value can be a human-readable search query that makes use of the Lucene 4.8 query parser syntax, as defined in the Lucene query parser documentation. In most cases, this query type is normally used for searching the index based on user input.

Value
string

Default: ""

The text content to look for in the specified document field. Its format depends on the value passed into the QueryType field.

Constructors

public Query();
Public Query()
public Query(string documentField, string value, TQueryTypes queryType);
Public Query(ByVal DocumentField As String, ByVal Value As String, ByVal QueryType As TQueryTypes)
public Query(string documentField, string value, TQueryTypes queryType, TOccurTypes occurType);
Public Query(ByVal DocumentField As String, ByVal Value As String, ByVal QueryType As TQueryTypes, ByVal OccurType As TOccurTypes)

ResultField Type

Holds information about a field from a search result document.

Remarks

This is used to access the data associated with a specific field in a search result document.

The following fields are available:

Fields

Name
string

Default: ""

The name of the document field. This is an identifier for the field that does not have to be unique.

Text
string

Default: ""

The text value of the document field.

Constructors

public ResultField();
Public ResultField()

Config Settings (Search Component)

The component accepts one or more of the following configuration settings. Configuration settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the component, access to these internal properties is provided through the Config method.

FuzzyMaxEdits:   The tolerance level for term variations in a fuzzy search.

Controls the level of tolerance for term variations in a fuzzy search.

Its value describes the amount of single-character edits (such as insertions, deletions, substitutions, or transpositions) that are allowed for a fuzzy query to be considered a match with an indexed term.

Valid values range from 0 to 2:

  • 0: No edits are allowed. This is the same as an exact match and will make the fuzzy query behave like a term query.
  • 1: Allows for one single-character edit. For example, a query for the word cat will match terms such as bat (one substitution), cats (one insertion), or at (one deletion).
  • 2: Allows up to two single-character edits. For example, a query for the word cat will match terms such as bzr (two substitutions), cots (one substitution and one insertion), or ca (one deletion).

By default, this setting is set to 2.

HighlightFieldIndex:   The index of a multi-valued field to highlight in the current search result document.

When Highlight is called and the current search result contains multiple fields with the specified name, this configuration setting can be used to determine the specific field that should be highlighted.

Its value is a zero-based index that only accounts for fields with the name specified in the Highlight method's FieldName parameter. It does not consider fields with different names.

LogLevel:   The level of detail that is logged through the Log event.

Controls the level of detail that is logged through the Log event. Possible values are:

0 (None - default) No events are logged.
1 (Info) Informational events are logged.
2 (Verbose) Detailed data are logged.
3 (Debug) Debug data are logged.

PhraseSlop:   The maximum number of positions by which terms in a phrase query can shift to qualify as a match for a document.

Controls the maximum number of positions by which the terms in a phrase query can shift to match a document.

For example, consider a document that contains the following phrases:

  1. First Second Third Fourth Fifth
  2. First Third Second Fourth Fifth
  3. Fifth Fourth Second Third First

If a phrase query with a slop value of 0 is performed for "First Second Third", only the first document will appear in the search results.

If the slop value is increased to 2, the query will match documents where the terms "First", "Second", and "Third" can be shifted by a maximum of two positions to match the phrase "First Second Third". In this case, only the first and second documents will appear in the search results.

Base Config Settings

BuildInfo:   Information about the product's build.

When queried, this setting will return a string containing information about the product's build.

GUIAvailable:   Whether or not a message loop is available for processing events.

In a GUI-based application, long-running blocking operations may cause the application to stop responding to input until the operation returns. The component will attempt to discover whether or not the application has a message loop and, if one is discovered, it will process events in that message loop during any such blocking operation.

In some non-GUI applications, an invalid message loop may be discovered that will result in errant behavior. In these cases, setting GUIAvailable to false will ensure that the component does not attempt to process external events.

LicenseInfo:   Information about the current license.

When queried, this setting will return a string containing information about the license this instance of a component is using. It will return the following information:

  • Product: The product the license is for.
  • Product Key: The key the license was generated from.
  • License Source: Where the license was found (e.g., RuntimeLicense, License File).
  • License Type: The type of license installed (e.g., Royalty Free, Single Server).
  • Last Valid Build: The last valid build number for which the license will work.
MaskSensitiveData:   Whether sensitive data is masked in log messages.

In certain circumstances it may be beneficial to mask sensitive data, like passwords, in log messages. Set this to true to mask sensitive data. The default is true.

This setting only works on these components: AS3Receiver, AS3Sender, Atom, Client(3DS), FTP, FTPServer, IMAP, OFTPClient, SSHClient, SCP, Server(3DS), Sexec, SFTP, SFTPServer, SSHServer, TCPClient, TCPServer.

UseFIPSCompliantAPI:   Tells the component whether or not to use FIPS certified APIs.

When set to true, the component will utilize the underlying operating system's certified APIs. Java editions, regardless of OS, utilize Bouncy Castle Federal Information Processing Standards (FIPS), while all other Windows editions make use of Microsoft security libraries.

FIPS mode can be enabled by setting the UseFIPSCompliantAPI configuration setting to true. This is a static setting that applies to all instances of all components of the toolkit within the process. It is recommended to enable or disable this setting once before the component has been used to establish a connection. Enabling FIPS while an instance of the component is active and connected may result in unexpected behavior.

For more details, please see the FIPS 140-2 Compliance article.

Note: This setting is applicable only on Windows.

Note: Enabling FIPS compliance requires a special license; please contact sales@nsoftware.com for details.

UseInternalSecurityAPI:   Whether or not to use the system security libraries or an internal implementation.

When set to false, the component will use the system security libraries by default to perform cryptographic functions where applicable. In this case, calls to unmanaged code will be made. In certain environments, this is not desirable. To use a completely managed security implementation, set this setting to true.

Setting this configuration setting to true tells the component to use the internal implementation instead of using the system security libraries.

On Windows, this setting is set to false by default. On Linux/macOS, this setting is set to true by default.

If using the .NET Standard Library, this setting will be true on all platforms. The .NET Standard library does not support using the system security libraries.

Note: This setting is static. The value set is applicable to all components used in the application.

When this value is set, the product's system dynamic link library (DLL) is no longer required as a reference, as all unmanaged code is stored in that file.

Trappable Errors (Search Component)