问题描述
{
"username": "Hermione Granger","fullName": "Hermione Jean Granger","dob": "19-September-1979","bloodStatus": "Muggle-Born","gender": "Female","parents": [
"Wendell Wilkins","Monica Wilkins"
]
}
当我使用索引时,我必须搜索整个短语,即 Hermione Granger。但我只想搜索 Hermione 并得到结果。
解决方法
Match
函数仅应用精确比较。不支持部分匹配。
一种可能适合您的方法是存储包含多个需要作为数组索引的值的字段。
当您索引值为数组的字段时,索引会为文档创建多个索引条目,以便可以使用任何一个数组项来匹配条目。请注意,此策略增加了所涉及的读写操作。
这是一个例子:
> CreateCollection({ name: "u" })
{
ref: Collection("u"),ts: 1618532727920000,history_days: 30,name: 'u'
}
> Create(Collection("u"),{ data: { n: ["Hermione","Granger"] }})
{
ref: Ref(Collection("u"),"295985674342892032"),ts: 1618532785650000,data: { n: [ 'Hermione','Granger' ] }
}
> Create(Collection("u"),{ data: { n: ["Harry","Potter"] }})
{
ref: Ref(Collection("u"),"295985684233060864"),ts: 1618532795080000,data: { n: [ 'Harry','Potter' ] }
}
> Create(Collection("u"),{ data: { n: ["Ginny","295985689713967616"),ts: 1618532800300000,data: { n: [ 'Ginny','Potter' ] }
}
> CreateIndex({
name: "u_by_n",source: Collection("u"),terms: [
{ field: ["data","n"] }
]
})
{
ref: Index("u_by_n"),ts: 1618533007000000,active: true,serialized: true,name: 'u_by_n3',terms: [ { field: [ 'data','n' ] } ],partitions: 1
}
> Paginate(Match(Index("u_by_n"),["Potter"]))
{
data: [
Ref(Collection("u"),Ref(Collection("u"),"295985689713967616")
]
}
请注意,您不能在单个字段中查询多个数组项:
> Paginate(Match(Index("u_by_n"),["Harry","Potter"]))
{ data: [] }
原因是索引在terms
中只定义了一个字段,成功匹配需要发送一个结构与terms
相同的数组到Match
。
为了能够搜索完整的用户名和用户名作为数组,我建议在您的文档中存储 username
字段的字符串和数组版本,例如username: 'Hermione Granger'
和 username_items: ['Hermione','Granger']
。然后创建一个索引用于搜索字符串字段,另一个用于数组字段,然后你可以任意搜索,