← Back to Documentation

Filters

Learn how to use filters to search over a subset of an index, based on specific properties of the indexed objects.


Filters are a very powerful idea which allow you to search over a subset of an index. For example, if you've indexed a set of people, you can use filters to search over only the people who are over a certain age, or located in a particular country.

When indexing an object, you can specify an arbitrary set of properties. If indexed, these properties can be used to filter the results of a search.

For example, let's index a set of people:

const people = [
  { name: "John", country: "canada" },
  { name: "Jane", country: "canada" },
  { name: "Patrick", country: "usa" },
  { name: "Peter", country: "usa" },
  { name: "Alex", country: "germany" },
  { name: "Alice", country: "germany" },
];
for (const person of people) {
  await operand.upsert({
    type: Object.ObjectType.TEXT,
    metadata: {
      value: {
        case: "text",
        value: {
          text: person.name,
        },
      },
    },
    properties: {
      properties: {
        country: {
          indexed: true,
          value: {
            case: "text",
            value: person.country,
          },
        },
      },
    },
  });
}

Now, let's search over all the people in Canada:

const results = await operand.searchWithin({
  query: "person",
  filter: {
    conditions: [
      {
        condition: {
          case: "property",
          value: {
            key: "country",
            property: {
              value: {
                case: "text",
                value: "canada",
              },
            },
          },
        },
      },
    ],
  },
});
console.log(results.matches.map((m) => `(${m.score}) ${m.content}`).flat());

Which prints:

[ '(0.13984157) John', '(0.09299691) Jane' ]

Supported Property Types

  • Text
  • Number
  • Text Array
  • Number Array

Supported Conditions

  • A property condition, i.e. a condition which checks for equality.
  • A range condition, i.e. is a number greater than or less than a certain value.
  • And/Or/Not conditions, allowing you to combine multiple conditions and use arbitrary boolean logic to filter.

Notes on Arrays

Arrays are treated as if the property key has multiple values. This means that:

  • If an object had a text array property of ["a", "b"], then a property condition of key: "a" or key: "b" would match.
  • If an object had a number array property of [1, 2, 3], then a range condition checks if any of the values are within the range specified.