# Search

{% hint style="success" %}
This is the official documentation of the `forestadmin-agent-django` and `forestadmin-agent-flask` Python agents.
{% endhint %}

In Forest Admin, pages that show lists of records have a free-text search bar on top of them.

![A search bar on the main Table View](/files/32OV2q1zWMT9vz8GBsrV)

### Search modes

2 search modes are supported: "normal" and "extended".

* All searches start by being a "normal" search.
* If the records users are looking for are not found, it is possible to trigger an "extended" search from the footer.

![Extended search call to action](/files/ACQHyXoB6eV5ZxWdOoNS)

### Default behavior

Natively, the search behavior is to seek value occurrences within columns of the Collection (in normal mode), and columns of the Collections of direct relations (in extended mode).

By default, Forest Admin will search only in specific columns, depending on their type:

| Column Type | Default search behavior                                                 |
| ----------- | ----------------------------------------------------------------------- |
| Enum        | Column is equal to the search string (case-insensitive).                |
| Number      | Column is equal to the search string (if the search string is numeric). |
| String      | Column contains the search string (case-insensitive).                   |
| Uuid        | Column is equal to the search string.                                   |
| Other types | Column is ignored by the default search handler.                        |

### Customization

If you want to make a column searchable, you must define the right operator to allow the search to be performed. Please refer to the [Operators to support](/developer-guide-agents-python/agent-customization/fields/filter.md#operators-to-support-to-enable-the-search) table to know which operator to define.

Alternatively, you may want to change how the search behaves in your admin panel.

For instance:

* search only on the columns that are relevant to your use case.
* use full-text indexes (i.e. Postgres `tsquery` and `tsvector`, Algolia, Elastic search, ...)

To customize the search behavior, you must define a handler that returns a [`ConditionTree`](/developer-guide-agents-python/data-sources/getting-started/queries/filters.md#condition-trees).

#### Making the search case-sensitive by default

In this example, we use the `searchExtended` condition to toggle between case-sensitive and insensitive searches.

```python
from forestadmin.datasource_toolkit.context.collection_context import CollectionCustomizationContext
from forestadmin.datasource_toolkit.interfaces.query.condition_tree.nodes.base import ConditionTree
from forestadmin.datasource_toolkit.interfaces.query.condition_tree.nodes.branch import ConditionTreeBranch
from forestadmin.datasource_toolkit.interfaces.query.condition_tree.nodes.leaf import ConditionTreeLeaf

def search_in_people(
    search_string, extended_search: bool, context: CollectionCustomizationContext
) -> ConditionTree:
    return ConditionTreeBranch(
        "or",
        [
            ConditionTreeLeaf("firstName", "contains", search_string),
            ConditionTreeLeaf("lastName", "contains", search_string),
        ],
    )

agent.customize_collection("people").replace_search(search_in_people)
```

#### Changing searched columns

```python
import re
from forestadmin.datasource_toolkit.context.collection_context import CollectionCustomizationContext
from forestadmin.datasource_toolkit.interfaces.query.condition_tree.nodes.base import ConditionTree
from forestadmin.datasource_toolkit.interfaces.query.condition_tree.nodes.branch import ConditionTreeBranch
from forestadmin.datasource_toolkit.interfaces.query.condition_tree.nodes.leaf import ConditionTreeLeaf

product_reference_regexp = r"^[a-f]{16}$"
barcode_regexp = r"^[0-9]{10}$"

async def search_in_products(
    search_string, extended_search: bool, context: CollectionCustomizationContext
) -> ConditionTree:
    # User is searching using a product reference.
    if re.match(product_reference_regexp, search_string):
        return ConditionTreeLeaf("reference", "equal", search_string)

    # User is search a barcode
    if re.match(barcode_regexp, search_string):
        return ConditionTreeLeaf("barCode", "equal", int(search_string))

    # User is searching something else, let's search in the product name only
    if not extended_search:
        return ConditionTreeLeaf("name", "contains", search_string)

    # In "extended" mode, we search on name, description and brand name
    return ConditionTreeBranch(
        "or",
        [
            ConditionTreeLeaf("name", "contains", search_string),
            ConditionTreeLeaf("description", "contains", search_string),
            ConditionTreeLeaf("brand:name", "equal", search_string),
        ],
    )

agent.customize_collection("products").replace_search(search_in_products)
```

#### Calling an external API

If your data is indexed using a SaaS, an external store, or a full-text index, you can call it in the search handler.

```python
from forestadmin.datasource_toolkit.context.collection_context import CollectionCustomizationContext
from forestadmin.datasource_toolkit.interfaces.query.condition_tree.nodes.base import ConditionTree
from forestadmin.datasource_toolkit.interfaces.query.condition_tree.nodes.leaf import ConditionTreeLeaf
from algoliasearch.search_client import SearchClient

client = SearchClient.create("YourApplicationID", "YourWriteAPIKey")
index = client.init_index("test_index")

async def search_in_products(
    search_string, extended_search: bool, context: CollectionCustomizationContext
) -> ConditionTree:
    hits = index.search(
        search_string,
        {"attributesToRetrieve": ["id"], "hitsPerPage": 50},
    )
    return ConditionTreeLeaf("id", "in", [hit["id"] for hit in hits])

agent.customize_collection("products").replace_search(search_in_products)
```

#### Disable the search

By default, the search bar is displayed when at least one field supports the operator used for search based on its type ([see this table](#default-behavior)).

You can remove the search bar by disabling the search on a collection:

```python
agent.customize_collection("product").disable_search()
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.forestadmin.com/developer-guide-agents-python/agent-customization/search.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
