如何在 FaunaDB 中进行文本搜索

How to text search in FaunaDB

如何根据属性搜索文档?

例如:我们有一个城市集合,我们想通过它们的名称属性进行搜索

我觉得这个主题没有很好地涵盖,所以我将 post 一个工作示例。

您必须在要搜索的属性的 ngram 列表上创建索引。

CreateIndex({
name: 'cities_by_ngrams',
source: [
    {
      // If your collections have the same property that you want to access you can pass a list to the collection
      collection: [Collection('cities')],
      fields: {
        wordparts: Query(
          Lambda('city',
            Distinct(
              Union(
                Let(
                  {
                    ngrams: q.Map(
                      // ngrams
                      [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
                      Lambda('i', NGram(
                        LowerCase(Select(['data', 'name'], Var('city'))),
                        Var('i'),
                        Var('i'),
                        )
                      )
                    )
                  },
                  Var('ngrams')
                )
              )
            )
          )
        )
      }
    }
  ],
terms: [
    {
      binding: 'wordparts'
    }
  ]
})

然后分页搜索

Map(
  Paginate(Match(Index('cities_by_ngrams'), 'londo')),
  Lambda('ref', Get(Var('ref')))
)

一个更简单的方法是拥有一个您计划为每个文档搜索的 ngram 列表,然后在该字段上创建索引。缺点是您必须在不需要的地方排除该字段。