如何在MongoDB中的嵌套字段上进行全文搜索?

时间:2020-03-30 15:44:28

标签: mongodb

我通过以下方式将本地化存储在MongoDB中

db.user.insertMany([
    {
        "name": {
            "en": "Frodo Baggins",
            "ru": "Фродо Беггинс"
        }
    },
    {
        "name": {
            "en": "Bilbo Baggins",
            "ru": "Бильбо Беггинс"
        }
    }
])

我知道我可以在所有字段上应用全文搜索索引

db.user.ensureIndex({ "$**": "text" })

但是我的文档还有很多其他我不想索引的信息。有什么方法可以指定仅索引名称字段内容?

1 个答案:

答案 0 :(得分:1)

您可以在name.en和name.ru上创建复合索引:

arcpy.env.workspace = edit_database
listBoundaries= arcpy.ListDatasets("*Boundaries")
for bounds in listBoundaries:
    inBound =os.path.join(edit_database, bounds)
    arcpy.env.workspace= inBound
    listBoundFC = arcpy.ListFeatureClasses()
    inpBound1 = []
    for BoundC in listBoundFC:
        inputBoundFC = os.path.join(inBound, BoundC)
        outputBoundUTM = multiple_replace(inputBoundFC, d)
        outputBoundWM = multiple_replace(inputBoundFC, e)
        inpBound2 = BoundC.replace('GTI_EDITING.DBO.', '')
        inpBound1.append(inpBound2)
        print inpBound1
        if inpBound1[f] not in outBound1:
            arcpy.CopyFeatures_management(inputBoundFC, outputBoundUTM)
            arcpy.CopyFeatures_management(inputBoundFC, outputBoundWM)
            print (outputBoundUTM + " and " + outputBoundWM + " have been updated

并使用此查询进行搜索:

db.user.createIndex(
   {
     "name.en": "text",
     "name.ru": "text"
   }
 )

您甚至可以添加得分值并进行排序:

db.user.find( { $text: { $search: "Baggins" } }) 

这将给出如下结果:

db.user
  .find({ $text: { $search: "Baggins" } }, { score: { $meta: "textScore" } })
  .sort({ score: { $meta: "textScore" } });
相关问题