#community-help

Defining Nested Fields in Typesense Schema

TLDR Ivy wanted to define a list of strings in a list of objects, and Jason suggested omitting the explicit field type for "products.ingredients". The schema generated the desired field type.

Powered by Struct AI

2

1

1

8
5mo
Solved
Join the chat
May 09, 2023 (5 months ago)
Ivy
Photo of md5-2f39998c05c5409f8c3521187ec34d4e
Ivy
09:20 PM
Hi all, I have a question about nested objects!

I'd like to have a schema like this:
{
    storeName: "Best Slice Shop"
    products: [{
       id: 123,
       name: pizza,
       ingredients: ["Tomatoes", "Garlic", ... ]
    }
]

But it looks like I can only define types on one layer deep (ref https://github.com/typesense/typesense/issues/227#issuecomment-1364072388), e.g.
{
    "enable_nested_fields": true,
    "name": "store",
    "fields": [
        {
            "name": "products",
            "type": "object[]"
        },
        {
            "name": "products.id",
            "type": "int[]"
        },
        {
            "name": "products.name",
            "type": "string[]"
        },
        {
            "name": "products.ingredients",
            "type": "string[][]" <-- doesn't work
        }
    ]
}

Is there a way to define a field to be list of strings on an list of objects field?

Thank you!!
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
09:22 PM
Interesting! Could you try this and see what happens:

{
            "name": "products.ingredients",
            "type": "string[]"
        }
09:23
Jason
09:23 PM
Hang on
09:23
Jason
09:23 PM
Letโ€™s try something else
09:24
Jason
09:24 PM
Could you use this schema:

{
    "enable_nested_fields": true,
    "name": "store",
    "fields": [
        {
            "name": "products",
            "type": "object[]"
    },
    ]
}

then index one of your documents and then look at the updated collection schema which Typesense generates and check the field type for products.ingredients?

1

Ivy
Photo of md5-2f39998c05c5409f8c3521187ec34d4e
Ivy
09:41 PM
Ok it looks like it's string[]! Interesting. Thank you!

    {
      "facet": false,
      "index": true,
      "infix": false,
      "locale": "",
      "name": "products.ingredients",
      "optional": true,
      "sort": false,
      "type": "string[]"
    },```
[ { "id": "123", "ingredients": [ "Tomatoes", "Garlic" ], "name": "pizza" } ]```

1

Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
09:42 PM
Btw, on a side note, the most generic field definition takes precedence in the collection schema. So if you have both products and products.ingredients explicitly listed, then products will take precedence and index all nested fields

1

Ivy
Photo of md5-2f39998c05c5409f8c3521187ec34d4e
Ivy
09:46 PM
Ah ok that makes sense and clarifies things, thank you!

1