> For the complete documentation index, see [llms.txt](https://docs.durohub.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.durohub.com/advanced-topics/searching-and-filtering.md).

# Searching and Filtering

Build powerful, precise queries to find exactly the components you need. This guide covers both our **Advanced Filter API** for programmatic queries and our **AI-Powered Filter API** for natural language searches.

{% hint style="info" %}
**New: Structured Query Syntax** — You can also use a `key:value` search syntax in the web app's search bar and via the `buildFilterFromQuery` / `filterWithQuery` APIs. See the [Search Query Syntax Reference](https://docs.durohub.com/advanced-topics/search-query-syntax.md) for the complete guide.
{% endhint %}

## Quick Start

Let's jump straight in. Here's a query to find all components in "Design" status that were modified in the last 30 days:

```graphql
query FilterComponents {
  component {
    filter(
      input: {
        and: [
          { status: { name: { eq: "Design" } } }
          { updatedAt: { after: "2024-12-01" } }
        ]
      }
    ) {
      edges {
        node {
          id
          name
          identifier {
            displayValue
          }
          status {
            name
          }
        }
      }
      totalCount
    }
  }
}
```

Or skip writing filters entirely—let AI do the work and get components in a single call:

```graphql
query SearchWithAI {
  component {
    filterWithAI(input: { query: "parts modified by Sarah in the last week" }) {
      components {
        id
        name
        identifier {
          displayValue
        }
      }
      totalCount
      interpretation
      success
    }
  }
}
```

That's it—one query, natural language in, components out!

{% hint style="info" %}
**New to the Duro API?** Make sure you've set up [authentication](https://docs.durohub.com/getting-started/authentication.md) first. All examples assume you have a valid API token.
{% endhint %}

***

## Part 1: Advanced Filter API

The Advanced Filter API gives you precise, programmatic control over component queries using a Linear-style AND/OR logic system.

### API Structure Overview

```
AdvancedComponentFilterInput
├── and: [ComponentFilterConditionInput]  ← All conditions must match
├── or: [ComponentFilterConditionInput]   ← Any condition can match
└── pagination: PaginationInput           ← Control page size and sorting
```

Each `ComponentFilterConditionInput` can filter by one or more fields:

| Field          | Type                          | Description                                                                                                                                                                                                                         |
| -------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`       | StatusFilterInput             | Filter by status ID, name, or type (DESIGN, PRODUCTION, etc.)                                                                                                                                                                       |
| `category`     | ComponentCategoryFilterInput  | Filter by category ID, name, or type (PART, ASSEMBLY, DOCUMENT)                                                                                                                                                                     |
| `state`        | StateFilterInput              | Filter by component state (RELEASED, MODIFIED)                                                                                                                                                                                      |
| `revision`     | RevisionFilterInput           | Filter by revision value with ordering support                                                                                                                                                                                      |
| `createdBy`    | UserFilterInput               | Filter by who created the component                                                                                                                                                                                                 |
| `updatedBy`    | UserFilterInput               | Filter by who last modified the component                                                                                                                                                                                           |
| `labels`       | LabelFilterInput              | Filter by assigned labels                                                                                                                                                                                                           |
| `isPinned`     | BooleanFilterInput            | Filter pinned/unpinned components                                                                                                                                                                                                   |
| `isBookmarked` | BooleanFilterInput            | Filter bookmarked components                                                                                                                                                                                                        |
| `createdAt`    | DateFilterInput               | Filter by creation date                                                                                                                                                                                                             |
| `updatedAt`    | DateFilterInput               | Filter by last update date                                                                                                                                                                                                          |
| `name`         | StringOperatorsInput          | Filter by component name (exact via `eq`, or `like`/`notLike` for patterns)                                                                                                                                                         |
| `identifier`   | IdentifierFilterInput         | Filter by CPN via `displayValue` (String Operators)                                                                                                                                                                                 |
| `eid`          | StringOperatorsInput          | Filter by EID (external ID). Negative operators (`neq`, `notIn`, `notContains`, `notLike`) also match components that have no EID                                                                                                   |
| `description`  | DescriptionFilterInput        | Full-text `contains`/`doesNotContain`, plus `like`/`notLike` pattern matching                                                                                                                                                       |
| `attribute`    | AttributeFilterConditionInput | Filter by an attribute value: `attributeId`, a `comparator` (`EQUALS`, `NOT_EQUALS`, `GREATER_THAN`, `LESS_THAN`, `GREATER_THAN_OR_EQUAL`, `LESS_THAN_OR_EQUAL`, `CONTAINS`, `DOES_NOT_CONTAIN`), a `value`, and an optional `unit` |
| `text`         | TextSearchInput               | Free-text search (`{ search: "..." }`) across name, CPN, EID, and description. Adds [search ranking](#search-ranking)                                                                                                               |
| `hasVariants`  | BooleanFilterInput            | Filter by whether the component is in a variant group                                                                                                                                                                               |
| `changeOrder`  | ComponentChangeOrderFilter    | Filter by the status of the change orders a component is on: `values` (`DRAFT`, `OPEN`, `RESOLVED`, `CLOSED`, or `NONE` for components on no change order) and `negate`                                                             |
| `sourcing`     | SourcingFilterInput           | Filter by manufacturer, MPN, distributor, DPN, or vendor in either role. See [Sourcing filters](#sourcing-filters)                                                                                                                  |

### Operators Reference

#### String Operators

Use these for filtering text fields like status names, category names, and labels:

| Operator      | Description                                                                                             | Example                                           |
| ------------- | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
| `eq`          | Exact match                                                                                             | `{ name: { eq: "Design" } }`                      |
| `neq`         | Not equal                                                                                               | `{ name: { neq: "Obsolete" } }`                   |
| `in`          | Match any in list                                                                                       | `{ name: { in: ["Design", "Development"] } }`     |
| `notIn`       | Exclude all in list                                                                                     | `{ name: { notIn: ["Obsolete", "Deprecated"] } }` |
| `contains`    | Substring match (case-insensitive)                                                                      | `{ name: { contains: "resistor" } }`              |
| `notContains` | Does not contain                                                                                        | `{ name: { notContains: "test" } }`               |
| `like`        | Pattern match, case-insensitive: `%` matches any sequence of characters, `_` matches a single character | `{ name: { like: "401-%" } }`                     |
| `notLike`     | Does not match the pattern                                                                              | `{ name: { notLike: "%draft%" } }`                |

{% hint style="info" %}
`like`/`notLike` match against a pattern where `%` stands for any sequence of characters and `_` for a single character. The search bar's `*` wildcard is **translated** to `%` before it reaches the API — so search-bar `cpn:401-*` is equivalent to `{ identifier: { displayValue: { like: "401-%" } } }`, and the negated `cpn!:401-*` to `notLike`. `like` itself does not understand `*`: a `*` in a `like` pattern is a literal asterisk. See [How `*` reaches the API](https://docs.durohub.com/advanced-topics/search-query-syntax.md#how-reaches-the-api) in the Search Query Syntax reference.
{% endhint %}

A `%` at the **start** of the pattern matches by suffix, which is how you find components that share a counter but differ by prefix:

```graphql
{ identifier: { displayValue: { like: "%-00100" } } }   # PCBA-00100, PCB-00100, EBOM-00100
{ name: { like: "%bracket%" } }                         # name contains "bracket"
```

{% hint style="warning" %}
`%` and `_` are wildcards in `like`, `notLike`, `contains`, and `notContains` alike: `contains` wraps your value as `%value%` without escaping it, so `{ contains: "REV_A" }` also matches `REVxA`. To match a literal `%` or `_`, escape it with a backslash inside `like`. In a GraphQL string the backslash itself is escaped, so `{ name: { like: "%50\\%%" } }` matches names containing `50%`.

In the search bar and the CPN / EID autocompletes, `%`, `_`, and `\` are escaped to literals only when the term contains a `*` wildcard (`\*` stands for a literal asterisk). Free text without `*` is passed through raw in `text.search`, so `%` and `_` still act as wildcards there.
{% endhint %}

#### Date Operators

Use these for `createdAt` and `updatedAt` fields:

| Operator                  | Description                         | Example                                                              |
| ------------------------- | ----------------------------------- | -------------------------------------------------------------------- |
| `before`                  | Date is before (exclusive)          | `{ before: "2024-06-01" }`                                           |
| `after`                   | Date is after (exclusive)           | `{ after: "2024-01-01" }`                                            |
| `on`                      | Exact date match (same day)         | `{ on: "2024-03-15" }`                                               |
| `rangeStart` + `rangeEnd` | Range, inclusive of both timestamps | `{ rangeStart: "2024-01-01", rangeEnd: "2024-03-31T23:59:59.999Z" }` |

{% hint style="warning" %}
Every bound is a timestamp, not a day. A date-only value such as `"2024-03-31"` means midnight UTC at the start of that day, so `rangeEnd: "2024-03-31"` leaves out everything created later on March 31. To include the whole end day, pass `rangeEnd: "2024-03-31T23:59:59.999Z"`, or use `before: "2024-04-01"`.
{% endhint %}

#### Revision Operators

Revisions support ordering comparisons. `lt` and `gt` order shorter values before longer ones, then alphabetically, ignoring case. That gives the expected order for single-scheme revisions:

* **Letter sequences**: A < B < ... < Z < AA < AB
* **Integers**: 1 < 2 < ... < 9 < 10 < 999

The comparison does not read your library's revision scheme, and multi-segment revisions are not compared segment by segment: `B.1` sorts before `A.10` because it is shorter.

`eq`, `neq`, `in`, and `notIn` ignore case and leading zeros, so `{ eq: "1" }` matches a stored `001`, and `{ eq: "b" }` matches `B`.

| Operator | Description  | Example                                      |
| -------- | ------------ | -------------------------------------------- |
| `eq`     | Exact match  | `{ value: { eq: "B" } }`                     |
| `neq`    | Not equal    | `{ value: { neq: "A" } }`                    |
| `in`     | Match any    | `{ value: { in: ["A", "B", "C"] } }`         |
| `notIn`  | Exclude all  | `{ value: { notIn: ["A"] } }`                |
| `lt`     | Less than    | `{ value: { lt: "C" } }` ← Matches A, B      |
| `gt`     | Greater than | `{ value: { gt: "B" } }` ← Matches C, D, ... |

#### Boolean Operators

Simple true/false matching:

| Operator    | Example                           |
| ----------- | --------------------------------- |
| `eq: true`  | `{ isPinned: { eq: true } }`      |
| `eq: false` | `{ isBookmarked: { eq: false } }` |

***

### Practical Examples

#### Example 1: Find Production-Ready Components

Find all components with a production-type status that have been released:

```graphql
query ProductionReadyComponents {
  component {
    filter(
      input: {
        and: [
          { status: { mapsTo: { eq: "PRODUCTION" } } }
          { state: { eq: RELEASED } }
        ]
      }
    ) {
      edges {
        node {
          id
          name
          identifier {
            displayValue
          }
          revisionValue
        }
      }
      totalCount
    }
  }
}
```

**cURL:**

```bash
curl 'https://api.durohub.com/graphql' \
  -H 'x-api-key: YOUR_API_TOKEN' \
  -H 'x-organization: @your-org-slug' \
  -H 'x-library: @your-org-slug/your-library-slug' \
  -H 'Content-Type: application/json' \
  -d '{
    "query": "query { component { filter(input: { and: [{ status: { mapsTo: { eq: \"PRODUCTION\" } } }, { state: { eq: RELEASED } }] }) { edges { node { id name identifier { displayValue } revisionValue } } totalCount } } }"
  }'
```

{% hint style="info" %}
**Required Headers:** All component queries require `x-organization` and `x-library` headers. `x-library` must name the library your API key was created in, and `x-organization` must be that library's organization. Use either slugs (e.g., `@acme/main-library`) or UUIDs.
{% endhint %}

{% hint style="info" %}
Using the EU or GovCloud region? Use your region's host — see [Endpoints](https://docs.durohub.com/readme.md#endpoints).
{% endhint %}

#### Example 2: Find Components by Category Type

Find all assemblies (not parts or documents):

```graphql
query FindAssemblies {
  component {
    filter(
      input: {
        and: [
          { category: { type: { eq: "ASSEMBLY" } } }
        ]
      }
    ) {
      edges {
        node {
          id
          name
          category {
            name
            type
          }
        }
      }
    }
  }
}
```

#### Example 3: Find Recently Modified Components by a Specific User

Find components that a specific user modified in the last 7 days:

```graphql
query RecentlyModifiedByUser {
  component {
    filter(
      input: {
        and: [
          { updatedBy: { id: { eq: "user-uuid-here" } } }
          { updatedAt: { after: "2024-12-25" } }
        ]
      }
    ) {
      edges {
        node {
          id
          name
          updatedAt
          updatedBy {
            id
            name
          }
        }
      }
    }
  }
}
```

#### Example 4: Using OR Logic

Find components that are either pinned OR have a specific label. `Component` has no labels field; to read a component's labels, use `labels.getEntityLabels` (shown after the query).

```graphql
query PinnedOrLabeled {
  component {
    filter(
      input: {
        or: [
          { isPinned: { eq: true } }
          { labels: { name: { eq: "Critical" } } }
        ]
      }
    ) {
      edges {
        node {
          id
          name
        }
      }
    }
  }
}
```

```graphql
query ComponentLabels($componentId: ID!) {
  labels {
    getEntityLabels(entityType: COMPONENT, entityId: $componentId) {
      id
      name
    }
  }
}
```

#### Example 5: Complex Multi-Condition Query

Find components that match ALL of these criteria:

* Status is "Design" or "Development"
* Category type is "PART"
* Revision is greater than "A"
* Not bookmarked

```graphql
query ComplexFilter {
  component {
    filter(
      input: {
        and: [
          { status: { name: { in: ["Design", "Development"] } } }
          { category: { type: { eq: "PART" } } }
          { revision: { value: { gt: "A" } } }
          { isBookmarked: { eq: false } }
        ]
      }
    ) {
      edges {
        node {
          id
          name
          identifier { displayValue }
          status { name }
          category { name type }
          revisionValue
        }
      }
      totalCount
    }
  }
}
```

#### Example 6: Date Range Query

Find components created in Q1 2024. `rangeEnd` carries the last millisecond of March 31 so the whole day is included (see [Date Operators](#date-operators)):

```graphql
query Q1Components {
  component {
    filter(
      input: {
        and: [
          {
            createdAt: {
              rangeStart: "2024-01-01"
              rangeEnd: "2024-03-31T23:59:59.999Z"
            }
          }
        ]
      }
    ) {
      edges {
        node {
          id
          name
          createdAt
        }
      }
    }
  }
}
```

### Pagination and Sorting

Control result size and ordering:

```graphql
query PaginatedResults {
  component {
    filter(
      input: {
        and: [{ state: { eq: RELEASED } }]
        pagination: {
          first: 25
          after: "cursor-from-previous-page"
          orderBy: { field: "CREATED_AT", direction: DESC }
        }
      }
    ) {
      edges {
        cursor
        node {
          id
          name
        }
      }
      pageInfo {
        hasNextPage
        endCursor
      }
      totalCount
    }
  }
}
```

**Available sort fields:** `"CREATED_AT"`, `"UPDATED_AT"`, `"NAME"`, `"CPN"`. `orderBy.field` is a string, so quote it. An unrecognized value falls back to `CREATED_AT DESC`.

**Directions:** `ASC`, `DESC`

**Page size:** `first` defaults to 100 and is capped at 100.

**Default sort order:** When `orderBy` is omitted and the filter has no `text` search, results are sorted by `CREATED_AT DESC` (most recently created first). This default applies to `findAll`, `filter`, `componentGroups`, and `componentsInGroup`.

#### Search ranking

When the filter includes a free-text `text` search, results are ranked into three tiers before any sort applies:

1. **Exact part number.** The CPN or EID equals the search, ignoring case.
2. **Part-number prefix.** The CPN or EID starts with the search, or fits its `*` wildcard pattern.
3. **Everything else that matched**: name, description, or a CPN/EID that contains the search somewhere in the middle.

`orderBy` (or the `CREATED_AT DESC` default) sorts components *within* each tier. It never moves a component into a different tier. Ranking only changes the order; the set of matches is the same as without it. Cursors from a ranked search carry the tier, so always pass `endCursor` back unchanged.

For example, in a library containing these components, `{ text: { search: "RES-100" } }` with no `orderBy` returns:

| Position | CPN           | Name                  | Created | Why it lands here                                                                                 |
| -------- | ------------- | --------------------- | ------- | ------------------------------------------------------------------------------------------------- |
| 1        | `RES-100`     | 10K Resistor          | 2023    | Tier 1: the CPN equals the search                                                                 |
| 2        | `RES-1004`    | 1M Resistor           | 2025    | Tier 2: the CPN starts with `RES-100`. Newest in its tier                                         |
| 3        | `RES-1001`    | 100K Resistor         | 2024    | Tier 2: the CPN starts with `RES-100`                                                             |
| 4        | `PCBA-0042`   | Divider, uses RES-100 | 2026    | Tier 3: only the name matches. It's the newest component, but tier 3 always follows tiers 1 and 2 |
| 5        | `KIT-RES-100` | Resistor kit          | 2025    | Tier 3: the CPN contains the search but doesn't start with it                                     |

Without the `text` search, the same components would come back newest first, with `PCBA-0042` on top. The ranking applies to `filter`, `componentGroups` previews, `componentsInGroup`, and the search bar (`filterWithQuery`). See [Free Text Search](https://docs.durohub.com/advanced-topics/search-query-syntax.md#free-text-search) for more worked examples.

### Grouping

In addition to filtering and sorting, you can group components by category, lifecycle status, type, last-modified user, label, or variant group using the `componentGroups` query. Each group returns a capped preview of its components with `totalCount` and cursor pagination for loading more.

The advanced filter works with grouped queries too — pass `advancedFilter` alongside `groupBy` to scope results before grouping.

See [Component Grouping](https://docs.durohub.com/advanced-topics/component-grouping.md) for the full guide.

### Filtering change orders by number

Change orders have their own filter, separate from the component operators above. `changeOrders.get` accepts an `advancedFilter` (`AdvancedChangeOrderFilterInput`) whose conditions include `nameOrEco`, which matches a change order's name **or** its number.

A change order's number is its type, a hyphen, and the library's counter padded to at least five digits (`ECO-00123`, `MCO-00012`). `nameOrEco` accepts the number as it appears in the app:

```graphql
query FindChangeOrderByNumber {
  changeOrders {
    get(
      advancedFilter: { and: [{ nameOrEco: { eq: "ECO-123" } }] }
      pagination: { first: 20 }
    ) {
      connection {
        edges {
          node {
            id
            sequentialId
            name
            status
          }
        }
        totalCount
      }
    }
  }
}
```

**Ways to write a number.** Each of these finds change order 123. Case and surrounding spaces do not matter.

| Value                                     | Notes                                                                                                                      |
| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `ECO-00123`                               | The number as shown in the app                                                                                             |
| `ECO-123`, `eco-123`, `eco 123`, `ECO123` | Without the padding, in any case, with or without a separator                                                              |
| `CO-123`, `CO 123`                        | Plain `CO`. It needs a separator: `CO123` is matched as text, so a name such as "CO2 sensor" is not read as change order 2 |
| `#123`                                    | A hash sign and the digits                                                                                                 |

**The prefix does not restrict the type.** All change-order types share one counter per library, so `eq: "ECO-12"` finds `MCO-00012` if that is what number 12 is.

**Supported operators.** `nameOrEco` supports `eq`, `neq`, `in`, `notIn` and `contains`.

Any other operator is refused with [`UNSUPPORTED_FILTER_OPERATOR`](https://docs.durohub.com/advanced-topics/error-handling.md#change-order-filter-errors). The other text conditions on this filter refuse the operators they do not apply in the same way; see [Filter Options](https://docs.durohub.com/core-concepts/change-orders.md#filter-options) for each one's list.

**`eq`, `neq`, `in` and `notIn`** match a change order whose whole name equals the value, or whose number is the one the value names. `in: ["ECO-12", "#34"]` finds change orders 12 and 34. `neq` and `notIn` leave out exactly what `eq` and `in` would find.

**`contains`** finds a change order whose name or number contains the value, so part of a number narrows the list:

* `contains: "ECO-0012"` finds change order 12, and also 120 through 129, whose numbers (`ECO-00120` to `ECO-00129`) contain that text.
* `contains: "bracket"` finds every change order with "bracket" in its name, in any case.
* `contains: "12"` is matched as text. It finds every change order whose name or number contains `12`, such as 12, 112, 120 and 1234. To find change order 12 alone, use `eq`.
* A written number is also matched as text. `contains: "CO-123"` finds change order 123, and any other whose number contains that text, such as `DCO-123456`.
* `%` and `_` have no special meaning. They are matched as written.

{% hint style="info" %}
To look up a change order by its counter alone, with no text matching, use the `filter` argument's `sequentialIds` (e.g. `filter: { sequentialIds: [123] }`). See [Change Orders](https://docs.durohub.com/core-concepts/change-orders.md#filter-options).
{% endhint %}

***

## Part 2: AI-Powered Search

Skip the filter syntax entirely. Describe what you're looking for in plain English, and get components back directly.

### Single-Call Search (Recommended)

The `filterWithAI` endpoint is the simplest way to search with natural language—one query, components returned directly:

```graphql
query SearchWithAI {
  component {
    filterWithAI(input: {
      query: "resistors modified by Sarah in the last 30 days"
      limit: 50
    }) {
      # The components you asked for
      components {
        id
        name
        identifier { displayValue }
        status { name }
        category { name }
      }
      totalCount

      # What the AI understood
      interpretation
      success

      # If you need to paginate beyond the limit
      filterInput

      # Anything that wasn't found
      notFoundEntities { type name }
    }
  }
}
```

**That's it.** Natural language in, components out. No two-step process, no filter syntax to learn.

### Input Options

| Field     | Type   | Default        | Description                               |
| --------- | ------ | -------------- | ----------------------------------------- |
| `query`   | String | Required       | Natural language query (3-500 characters) |
| `limit`   | Int    | 20             | Max components to return (1-100)          |
| `orderBy` | Object | createdAt DESC | Sort field and direction                  |

### Response Structure

| Field              | Type    | Description                                           |
| ------------------ | ------- | ----------------------------------------------------- |
| `components`       | Array   | The matching components (up to `limit`)               |
| `totalCount`       | Int     | Total matches in the library (may exceed `limit`)     |
| `interpretation`   | String  | Human-readable summary of what was understood         |
| `success`          | Boolean | Whether the AI understood your query                  |
| `filterInput`      | JSON    | The generated filter (for pagination—see below)       |
| `filterValues`     | Array   | UI-friendly format with field/comparator/displayLabel |
| `matchMode`        | String  | `"all"` (AND) or `"any"` (OR)                         |
| `notFoundEntities` | Array?  | Entities mentioned but not found                      |
| `error`            | String? | Error message if generation failed                    |

{% hint style="success" %}
**Need more than 100 results?** Use the `filterInput` field (returned as JSON) and pass it to `component.filter` for cursor-based pagination.
{% endhint %}

### cURL Example

```bash
curl 'https://api.durohub.com/graphql' \
  -H 'x-api-key: YOUR_API_TOKEN' \
  -H 'x-organization: @your-org-slug' \
  -H 'x-library: @your-org-slug/your-library-slug' \
  -H 'Content-Type: application/json' \
  -d '{
    "query": "query { component { filterWithAI(input: { query: \"parts in production status\", limit: 25 }) { components { id name identifier { displayValue } } totalCount interpretation success } } }"
  }'
```

### Example Response

**Query:** `"resistors modified by Sarah in the last 30 days"`

```json
{
  "data": {
    "component": {
      "filterWithAI": {
        "components": [
          { "id": "comp-1", "name": "10K Resistor", "identifier": { "displayValue": "RES-001" } },
          { "id": "comp-2", "name": "100K Resistor", "identifier": { "displayValue": "RES-002" } }
        ],
        "totalCount": 47,
        "interpretation": "Showing Resistors modified by Sarah Chen in the last 30 days",
        "success": true,
        "filterInput": {
          "and": [
            { "category": { "id": { "eq": "cat-resistors" } } },
            { "updatedBy": { "id": { "eq": "user-sarah" } } },
            { "updatedAt": { "after": "2024-12-10T00:00:00.000Z" } }
          ]
        },
        "matchMode": "all",
        "notFoundEntities": null
      }
    }
  }
}
```

### Handling Partial Matches

If the AI can't find something you mentioned, it tells you:

**Query:** `"resistors modified by John Smith"`

```json
{
  "components": [{ "id": "...", "name": "10K Resistor" }],
  "totalCount": 23,
  "interpretation": "Showing Resistors",
  "success": true,
  "notFoundEntities": [
    { "type": "USER", "name": "John Smith" }
  ]
}
```

The query still runs with the filters it *could* resolve. Check `notFoundEntities` to see what was missing. `type` is one of `USER`, `CATEGORY`, `STATUS`, `LABEL`, or `CHANGE_ORDER_STATUS`.

### Best Practices

{% hint style="success" %}
**Be specific with names.** Say "Design" not "designing" or "in design phase."
{% endhint %}

{% hint style="success" %}
**Use full names for users.** "Sarah Chen" works better than just "Sarah."
{% endhint %}

{% hint style="success" %}
**Combine concepts with AND/OR.** "resistors OR capacitors modified last week" → results in OR match mode.
{% endhint %}

{% hint style="warning" %}
**Check `notFoundEntities`.** If a user or status isn't found, the AI will tell you—you may have a typo or need to use a different name.
{% endhint %}

### Complete Python Example

```python
import requests

API_URL = "https://api.durohub.com/graphql"
HEADERS = {
    "x-api-key": "YOUR_API_TOKEN",
    "x-organization": "@acme",
    "x-library": "@acme/electronics",
    "Content-Type": "application/json"
}

def search_components(query: str, limit: int = 50):
    """Search components using natural language - single API call!"""

    graphql_query = """
    query SearchWithAI($query: String!, $limit: Int) {
      component {
        filterWithAI(input: { query: $query, limit: $limit }) {
          components {
            id
            name
            identifier { displayValue }
            status { name }
            category { name }
          }
          totalCount
          interpretation
          success
          notFoundEntities { type name }
          filterInput
        }
      }
    }
    """

    response = requests.post(API_URL, headers=HEADERS, json={
        "query": graphql_query,
        "variables": {"query": query, "limit": limit}
    })

    result = response.json()["data"]["component"]["filterWithAI"]

    print(f"AI interpretation: {result['interpretation']}")
    print(f"Found {result['totalCount']} components (showing {len(result['components'])})")

    if result.get("notFoundEntities"):
        print(f"Warning - not found: {result['notFoundEntities']}")

    return result["components"]


# Usage
if __name__ == "__main__":
    components = search_components("resistors modified by Sarah Chen in the last 30 days")
    for comp in components:
        print(f"  - {comp['identifier']['displayValue']}: {comp['name']}")
```

### Paginating Large Result Sets

If `totalCount` exceeds your `limit`, use the `filterInput` field to paginate with `component.filter`.

`filterWithAI` returns components but **no cursors**, so its own response cannot be paged from. Use it once to build the filter, then read every page — including the first — through `component.filter`:

```python
def search_with_ai(query: str, limit: int = 20):
    """Run filterWithAI and return its whole result, including filterInput."""

    graphql_query = """
    query SearchWithAI($query: String!, $limit: Int) {
      component {
        filterWithAI(input: { query: $query, limit: $limit }) {
          success
          error
          interpretation
          filterInput
        }
      }
    }
    """

    response = requests.post(API_URL, headers=HEADERS, json={
        "query": graphql_query,
        "variables": {"query": query, "limit": limit}
    })
    return response.json()["data"]["component"]["filterWithAI"]


def fetch_page(filter_input: dict, after: str | None = None):
    """Read one page of component.filter for a filter built by filterWithAI."""

    graphql_query = """
    query FilterPage($input: AdvancedComponentFilterInput!) {
      component {
        filter(input: $input) {
          edges {
            node {
              id
              name
              identifier { displayValue }
            }
          }
          pageInfo { hasNextPage endCursor }
        }
      }
    }
    """

    pagination = {"first": 100}
    if after:
        pagination["after"] = after

    response = requests.post(API_URL, headers=HEADERS, json={
        "query": graphql_query,
        "variables": {"input": {**filter_input, "pagination": pagination}}
    })
    connection = response.json()["data"]["component"]["filter"]
    return {
        "components": [edge["node"] for edge in connection["edges"]],
        "hasNextPage": connection["pageInfo"]["hasNextPage"],
        "endCursor": connection["pageInfo"]["endCursor"],
    }


def search_all_components(query: str):
    """Search with AI, then page through every result."""

    # One AI call, used only to build the filter. `limit=1` because whatever it
    # returns here gets discarded — the pages come from component.filter.
    result = search_with_ai(query, limit=1)

    if not result["success"]:
        raise RuntimeError(result["error"])

    filter_input = result["filterInput"]

    all_components = []
    cursor = None
    while True:
        page = fetch_page(filter_input, after=cursor)
        all_components.extend(page["components"])
        if not page["hasNextPage"]:
            break
        cursor = page["endCursor"]

    return all_components
```

{% hint style="warning" %}
Do not keep `filterWithAI`'s own `components` and then start paging `component.filter` from `after=None`. That re-reads the same rows from the beginning and appends them to what you already have, duplicating the first page.
{% endhint %}

### Two-Step Approach (Advanced)

If you're building a filter UI where users need to see and edit individual filter conditions before executing, use `buildFilterWithAI` instead:

```graphql
query BuildFilter {
  component {
    buildFilterWithAI(input: { query: "parts in design" }) {
      filterValues {
        field
        comparator
        value
        displayLabel
      }
      matchMode
      interpretation
      success
    }
  }
}
```

This returns structured `filterValues` that you can display as editable filter pills. Once the user confirms, pass the filter to `component.filter`.

{% hint style="info" %}
**Wildcard pills carry `*`, not `%`.** A `filterValues` entry with the `matches` or `doesNotMatch` comparator holds the user's pattern as typed (`TW1550*`, `\*` for a literal asterisk, `%` and `_` literal). The `filterInput` returned alongside it already holds the translated `like` / `notLike` pattern (`TW1550%`). `buildFilterFromQuery` behaves the same way. If you build your own `AdvancedComponentFilterInput` from `filterValues`, translate `*` to `%`, `\*` to `*`, and backslash-escape literal `%`, `_`, and `\` before using `like` / `notLike`; do not pass the `*` pattern through as-is.
{% endhint %}

***

## Part 3: Tips and Best Practices

### Performance Tips

1. **Use `and` over `or` when possible.** AND queries are generally faster as they narrow results.
2. **Filter by indexed fields first.** Status, category, and state are highly optimized.
3. **Paginate large results.** Use `first: 50` and cursor-based pagination rather than fetching everything.

### Common Patterns

#### "Recently modified by me"

```graphql
{
  and: [
    { updatedBy: { id: { eq: "YOUR_USER_ID" } } }
    { updatedAt: { after: "2024-12-01" } }
  ]
}
```

#### "All released parts except obsolete"

```graphql
{
  and: [
    { category: { type: { eq: "PART" } } }
    { state: { eq: RELEASED } }
    { status: { mapsTo: { neq: "OBSOLETE" } } }
  ]
}
```

#### "Components with any of these labels"

```graphql
{
  or: [
    { labels: { name: { eq: "Critical" } } }
    { labels: { name: { eq: "Urgent" } } }
    { labels: { name: { eq: "Review Needed" } } }
  ]
}
```

#### "Early revisions only"

```graphql
{
  and: [
    { revision: { value: { in: ["A", "B", "1", "2"] } } }
  ]
}
```

#### "Anything we get from a supplier, made or sold"

```graphql
{
  and: [
    { sourcing: { vendor: { in: ["McMaster-Carr", "McMaster"] } } }
  ]
}
```

#### "Released parts with no Digi-Key quote"

```graphql
{
  and: [
    { state: { eq: RELEASED } }
    { sourcing: { distributor: { notContains: "digi-key" } } }
  ]
}
```

### Debugging Filters

1. **Start simple.** Test one condition at a time before combining.
2. **Check your field paths.** `status.name` vs `status.mapsTo` vs `status.id` target different things.
3. **Verify IDs exist.** If filtering by UUID, ensure the status/category/user actually exists in your library.
4. **Watch for empty results.** An overly specific `and` query might match nothing. Try loosening conditions.

***

## Complete API Reference

### AdvancedComponentFilterInput

```graphql
input AdvancedComponentFilterInput {
  """All conditions must match (AND logic)"""
  and: [ComponentFilterConditionInput!]

  """Any condition can match (OR logic)"""
  or: [ComponentFilterConditionInput!]

  """Pagination options"""
  pagination: PaginationInput
}
```

### ComponentFilterConditionInput

```graphql
input ComponentFilterConditionInput {
  status: StatusFilterInput
  category: ComponentCategoryFilterInput
  state: StateFilterInput
  revision: RevisionFilterInput
  createdBy: UserFilterInput
  updatedBy: UserFilterInput
  labels: LabelFilterInput
  isPinned: BooleanFilterInput
  isBookmarked: BooleanFilterInput
  createdAt: DateFilterInput
  updatedAt: DateFilterInput
  identifier: IdentifierFilterInput
  name: StringOperatorsInput

  """EID / external ID; negations also match components without an EID"""
  eid: StringOperatorsInput
  description: DescriptionFilterInput
  attribute: AttributeFilterConditionInput

  """Free-text search across name, CPN, EID, and description"""
  text: TextSearchInput
  hasVariants: BooleanFilterInput
  changeOrder: ComponentChangeOrderFilter
  sourcing: SourcingFilterInput
}
```

### IdentifierFilterInput

```graphql
input IdentifierFilterInput {
  """Filter by CPN display value"""
  displayValue: StringOperatorsInput
}
```

### DescriptionFilterInput

```graphql
input DescriptionFilterInput {
  """Full-text match with stemming, plus fuzzy (trigram) similarity"""
  contains: String

  """Exact inverse of contains"""
  doesNotContain: String

  """Wildcard LIKE pattern"""
  like: String

  """Wildcard NOT LIKE pattern"""
  notLike: String
}
```

### AttributeFilterConditionInput

```graphql
input AttributeFilterConditionInput {
  attributeId: ID!
  comparator: AttributeComparator!
  value: String!
  unit: String
}

enum AttributeComparator {
  EQUALS
  NOT_EQUALS
  GREATER_THAN
  LESS_THAN
  GREATER_THAN_OR_EQUAL
  LESS_THAN_OR_EQUAL
  CONTAINS
  DOES_NOT_CONTAIN
}
```

### TextSearchInput

```graphql
input TextSearchInput {
  search: String!
}
```

### ComponentChangeOrderFilter

```graphql
input ComponentChangeOrderFilter {
  """Change order status values, plus NONE for components on no change order"""
  values: [ChangeOrderFilterValue!]!

  """Invert the match"""
  negate: Boolean! = false
}
```

`values` accepts `DRAFT`, `OPEN`, `RESOLVED`, `CLOSED`, and `NONE`.

### StateFilterInput

```graphql
input StateFilterInput {
  eq: ComponentState
  neq: ComponentState
}
```

### UserFilterInput

```graphql
input UserFilterInput {
  """Filter by user ID"""
  id: StringOperatorsInput
}
```

### StatusFilterInput

```graphql
input StatusFilterInput {
  """Filter by status UUID"""
  id: StringOperatorsInput

  """Filter by custom status name"""
  name: StringOperatorsInput

  """Filter by status type: DESIGN, DEVELOPMENT, PRODUCTION, MAINTENANCE, OBSOLETE"""
  mapsTo: StringOperatorsInput
}
```

### ComponentCategoryFilterInput

```graphql
input ComponentCategoryFilterInput {
  """Filter by category UUID"""
  id: StringOperatorsInput

  """Filter by category name"""
  name: StringOperatorsInput

  """Filter by category type: ASSEMBLY, PART, DOCUMENT"""
  type: StringOperatorsInput
}
```

### LabelFilterInput

```graphql
input LabelFilterInput {
  """Filter by label name (the unique identifier for labels)"""
  name: StringOperatorsInput
}
```

{% hint style="info" %}
**Labels filter by name, not ID.** Unlike other entities, labels are matched using their `name` field (e.g., `"Critical"`, `"High Priority"`). This is the canonical identifier for labels in the filter system.
{% endhint %}

### SourcingFilterInput

```graphql
input SourcingFilterInput {
  """Manufacturer name. Matches vendor aliases as well as the canonical name."""
  manufacturer: StringOperatorsInput

  """Manufacturer part number"""
  mpn: StringOperatorsInput

  """Distributor name. Matches vendor aliases as well as the canonical name."""
  distributor: StringOperatorsInput

  """Vendor name in either role, manufacturer or distributor. Matches vendor aliases as well as the canonical name."""
  vendor: StringOperatorsInput

  """Distributor part number"""
  dpn: StringOperatorsInput
}
```

#### Sourcing filters

`sourcing` matches against a component's manufacturer parts and distributor quotes, not its own fields. A component can have many of each, which shapes how the operators behave:

* **Positive operators** (`eq`, `in`, `contains`, `like`) match when **any** part or quote matches.
* **Negative operators** (`neq`, `notIn`, `notContains`, `notLike`) match when **no** part or quote matches. A component with one McMaster-Carr part and one Vishay part is excluded by `{ manufacturer: { neq: "McMaster-Carr" } }`. A component with no sourcing at all matches every negative operator.
* **Names compare case-insensitively** against the canonical vendor name and its aliases. `eq` and `in` need the whole name or alias. Use `contains` when you have only part of the name.
* **`vendor` ignores the role.** It matches a company that manufactures a part or distributes a quote, so `{ vendor: { notIn: ["Acme"] } }` drops anything Acme makes **or** sells. Use `manufacturer` or `distributor` when the role matters.
* **`mpn` and `dpn` compare literally for `eq`, `neq`, `in`, and `notIn`.** `_` and `%` are ordinary characters there. `like` and `notLike` treat them as pattern characters, as they do on every other field.

The [search bar keys](https://docs.durohub.com/advanced-topics/search-query-syntax.md#sourcing-keys) `mfg:`, `mpn:`, `dist:`, `vendor:` (or `supplier:`), and `dpn:` build these filters.

### StringOperatorsInput

```graphql
input StringOperatorsInput {
  eq: String
  neq: String
  in: [String!]
  notIn: [String!]
  contains: String
  notContains: String

  """Wildcard match (case-insensitive). % = any chars, _ = single char. Backslash escapes."""
  like: String

  """Wildcard non-match (case-insensitive). See like."""
  notLike: String
}
```

### DateFilterInput

```graphql
input DateFilterInput {
  """Date is before this value (exclusive)"""
  before: String

  """Date is after this value (exclusive)"""
  after: String

  """Date equals this value (same day)"""
  on: String

  """Start of range (inclusive timestamp)"""
  rangeStart: String

  """End of range (inclusive timestamp; a date-only value means midnight UTC)"""
  rangeEnd: String
}
```

### RevisionOperatorsInput

```graphql
input RevisionOperatorsInput {
  eq: String
  neq: String
  in: [String!]
  notIn: [String!]
  lt: String
  gt: String
}
```

### BooleanFilterInput

```graphql
input BooleanFilterInput {
  eq: Boolean
}
```

### FilterWithAiInput (Recommended)

```graphql
input FilterWithAiInput {
  """Natural language query (3-500 characters)"""
  query: String!

  """Max components to return (default: 20, max: 100)"""
  limit: Int = 20

  """Sort order for results"""
  orderBy: ComponentOrderInput
}
```

### FilterWithAiOutput

```graphql
type FilterWithAiOutput {
  """The matching components"""
  components: [Component!]!

  """Total count of matching components in the library"""
  totalCount: Int!

  """Match mode: 'all' (AND) or 'any' (OR)"""
  matchMode: String!

  """Whether the AI understood your query"""
  success: Boolean!

  """Human-readable interpretation of the filters"""
  interpretation: String

  """UI-friendly filter format"""
  filterValues: [FilterValueOutput!]!

  """The generated filter as JSON (for pagination with component.filter)"""
  filterInput: JSON

  """Entities mentioned but not found in the library"""
  notFoundEntities: [NotFoundEntity!]

  """Error message if generation failed"""
  error: String
}
```

### BuildAiFilterInput (Two-Step Approach)

```graphql
input BuildAiFilterInput {
  """Natural language query (3-500 characters)"""
  query: String!
}
```

### AiFilterResult

```graphql
type AiFilterResult {
  """Ready-to-use filter - pass directly to component.filter(input:)"""
  filterInput: AdvancedComponentFilterOutput

  """UI-friendly filter format with field/comparator/value/displayLabel"""
  filterValues: [FilterValueOutput!]!

  """Match mode: 'all' (AND) or 'any' (OR)"""
  matchMode: String!

  """Whether filter generation succeeded"""
  success: Boolean!

  """Error message if generation failed"""
  error: String

  """Entities mentioned but not found in the library"""
  notFoundEntities: [NotFoundEntity!]

  """Human-readable interpretation of the filters"""
  interpretation: String
}
```

### AdvancedComponentFilterOutput

The `filterInput` field returns this type, which mirrors `AdvancedComponentFilterInput`:

```graphql
type AdvancedComponentFilterOutput {
  and: [ComponentFilterConditionOutput!]
  or: [ComponentFilterConditionOutput!]
}

type ComponentFilterConditionOutput {
  status: StatusFilterOutput
  category: CategoryFilterOutput
  state: StateFilterOutput
  revision: RevisionFilterOutput
  createdBy: UserFilterOutput
  updatedBy: UserFilterOutput
  labels: LabelFilterOutput
  isPinned: BooleanFilterOutput
  isBookmarked: BooleanFilterOutput
  createdAt: DateFilterOutput
  updatedAt: DateFilterOutput
  identifier: IdentifierFilterOutput
  name: StringOperatorsOutput
  eid: StringOperatorsOutput
  description: DescriptionFilterOutput
  attribute: AttributeFilterConditionOutput
  text: TextSearchOutput
  changeOrder: ComponentChangeOrderFilterOutput
  sourcing: SourcingFilterOutput
}

type StatusFilterOutput {
  id: StringOperatorsOutput
  mapsTo: StringOperatorsOutput
}

type CategoryFilterOutput {
  id: StringOperatorsOutput
  type: StringOperatorsOutput
}
```

The output carries IDs rather than names: a status or category the AI resolved by name comes back as `id`.

***

## Next Steps

* Learn about controlling access with [Role-Based Access Control](https://docs.durohub.com/advanced-topics/rbac.md)
* Set up [Webhooks](https://docs.durohub.com/advanced-topics/webhooks.md) to react to component changes in real-time
* Explore [Change Order Workflows](https://docs.durohub.com/library-configuration/change-order-workflows.md) for managing engineering changes
* Skip the queries entirely — the [Duro MCP Server](https://docs.durohub.com/ai-integration/mcp.md) puts this same search behind plain-language questions


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.durohub.com/advanced-topics/searching-and-filtering.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
