Quick Start Guide

This guide provides a quick overview of how to set up and start using GroupDocs.Search for Python via .NET. The library builds an index over your documents, searches it with a rich query language, and shows where in each document the found words are.

Prerequisites

To proceed, make sure you have:

  1. Configured environment as described in the System Requirements topic.
  2. Optionally you may Get a Temporary License to test all the product features.

Set Up Your Development Environment

For best practices, use a virtual environment to manage dependencies in Python applications. Learn more about virtual environments at the Create and Use Virtual Environments documentation topic.

Create and Activate a Virtual Environment

Create a virtual environment:

py -m venv .venv
python3 -m venv .venv
python3 -m venv .venv

Activate a virtual environment:

.venv\Scripts\activate
source .venv/bin/activate
source .venv/bin/activate

Install groupdocs-search-net Package

After activating the virtual environment, run the following command in your terminal to install the latest version of the package:

py -m pip install groupdocs-search-net
python3 -m pip install groupdocs-search-net
python3 -m pip install groupdocs-search-net

Ensure the package is installed successfully. You should see the message

Successfully installed groupdocs-search-net-*
Note
Until PyPI carries the 26.10 wheels, install the wheel for your platform from the GroupDocs Releases website instead, as described in Install from a Pre-Downloaded Wheel.

Example 1: Index and search documents

To quickly test the library, let’s index a folder of documents and search it for a phrase.

import os

from groupdocs.search import Index, License

def search_documents():
    # Optionally set a license
    license_path = os.path.abspath("./GroupDocs.Search.lic")
    if os.path.exists(license_path):
        License().set_license(license_path)

    # Create an index in the "index" folder and index the "documents" folder
    with Index("./index") as index:
        index.add("./documents")

        # A phrase in double quotes matches these words in this order
        result = index.search('"theory of relativity"')

        print("Documents found:", result.document_count)
        print("Occurrences found:", result.occurrence_count)
        # Most relevant first: the result lists the documents in the order they were indexed
        for document in sorted(result, key=lambda found: found.relevance, reverse=True):
            print(os.path.basename(document.document_info.file_path), "-", document.occurrence_count, "occurrences")

if __name__ == "__main__":
    search_documents()
Documents found: 2
Occurrences found: 3
einstein.txt - 2 occurrences
relativity.txt - 1 occurrences

Download full output

Your folder tree should look similar to the following directory structure:

📂 demo-app
 ├──search_documents.py
 ├──📂 documents
 │   ├──einstein.txt
 │   ├──nobel-prize-1921.txt
 │   ├──relativity.txt
 │   └──time.txt
 └──GroupDocs.Search.lic (Optionally)

Run the App

py search_documents.py
python3 search_documents.py
python3 search_documents.py

The first run creates the index folder next to the script. Later runs open the index from there, and add() indexes only the documents that are new or have changed. After running the app you can deactivate the virtual environment by executing deactivate or closing your shell.

Explanation

  • Index("./index"): Creates an index in the index folder, or opens the index already stored there. Used as a context manager so the index is closed when the block ends.
  • index.add("./documents"): Indexes every document of a supported format in the folder and its subfolders.
  • index.search('"theory of relativity"'): Runs a query. The double quotes make it a phrase: the words must appear together and in this order.
  • result.document_count / result.occurrence_count: The numbers of documents found and of occurrences in all of them. Iterating over result gives each found document, in the order the documents were indexed, which follows the file system: name order on Windows, but not on Linux. Sorting by relevance lists the most relevant first on every system.

Example 2: Search with a typo

In this example we search for a misspelled name. Fuzzy search finds the words that differ from the query by a few characters.

import os

from groupdocs.search import Index, License
from groupdocs.search.options import SearchOptions

def fuzzy_search():
    # Optionally set a license
    license_path = os.path.abspath("./GroupDocs.Search.lic")
    if os.path.exists(license_path):
        License().set_license(license_path)

    with Index("./index") as index:
        index.add("./documents")

        # Fuzzy search also finds words that differ from the query by a few characters
        options = SearchOptions()
        options.fuzzy_search.enabled = True

        result = index.search("Einstien", options)
        print("Documents found:", result.document_count)
        for document in sorted(result, key=lambda found: found.relevance, reverse=True):
            # The words of the document that matched the query
            words = set()
            for field in document.found_fields:
                words.update(field.terms)
            print(os.path.basename(document.document_info.file_path), "-", ", ".join(sorted(words)))

if __name__ == "__main__":
    fuzzy_search()
Documents found: 2
einstein.txt - einstein
nobel-prize-1921.txt - einstein

Download full output

Run the App

py fuzzy_search.py
python3 fuzzy_search.py
python3 fuzzy_search.py

Explanation

  • SearchOptions(): Holds the settings of one search. fuzzy_search.enabled = True turns on fuzzy search with its default similarity level.
  • index.search("Einstien", options): Searches with these options. Without them, the misspelled query finds nothing.
  • document.found_fields: The fields of a found document that matched, such as content and filename, each with the words it found in terms.

Example 3: Highlight the found words

Sometimes you need to show where in a document a word was found. A fragment highlighter returns the found words with a few words of context around each.

import os

from groupdocs.search import Index, License
from groupdocs.search.highlighters import FragmentHighlighter
from groupdocs.search.options import HighlightOptions, OutputFormat

def highlight_results():
    # Optionally set a license
    license_path = os.path.abspath("./GroupDocs.Search.lic")
    if os.path.exists(license_path):
        License().set_license(license_path)

    with Index("./index") as index:
        index.add("./documents")
        result = index.search("gravity")

        # Four words of context on each side of a found word, which is put in brackets
        options = HighlightOptions()
        options.terms_before = 4
        options.terms_after = 4
        options.term_highlight_start_tag = "["
        options.term_highlight_end_tag = "]"

        for document in sorted(result, key=lambda found: found.relevance, reverse=True):
            highlighter = FragmentHighlighter(OutputFormat.PLAIN_TEXT)
            index.highlight(document, highlighter, options)
            print(os.path.basename(document.document_info.file_path))
            for container in highlighter.get_result():
                for fragment in container.get_fragments():
                    print("   ", " ".join(fragment.split()))

if __name__ == "__main__":
    highlight_results()
relativity.txt
    in the absence of [gravity]. General relativity explains the
einstein.txt
    theory of relativity described [gravity] as the curvature of

Download full output

Run the App

py highlight_results.py
python3 highlight_results.py
python3 highlight_results.py

Explanation

  • HighlightOptions(): How many words of context to keep before and after each found word (terms_before, terms_after), and the tags put around the found words.
  • FragmentHighlighter(OutputFormat.PLAIN_TEXT): Collects the fragments as plain text. OutputFormat.HTML marks the found words with HTML instead.
  • index.highlight(document, highlighter, options): Highlights the found words of one found document. get_result() then gives the fragments of each field.

Next Steps

After completing the basics, explore additional resources to enhance your usage:

Close
Loading

Analyzing your prompt, please hold on...

An error occurred while retrieving the results. Please refresh the page and try again.