MongodDB中的文本搜索

时间:2017-11-10 02:05:52

标签: javascript mongodb nlp keyword-search

考虑以下代码:

Transactions: [
               {name: 123, content: "Starbucks Coffee"},
               {name: 456, content: "Peets Coffee"},
               {name: 789, content: "Amazon gift card"},
               {name: 646, content: "amazon gift card"},
               {name: 779, content: "Acme Corp deposit cheque"},
               {name: 606, content: "acme corp deposit cheque"},
               {name: 879, content: "Dunkin-Donuts"},
               {name: 656, content: "Dunkin Donuts"}
              ];

我需要编写一个MongoDB框架,它执行以下操作:

案例1。)

输入:" Acme Corp"或" acme Corp"或" Acme corp"或" acme corp"

预期产出:

       [
        {name: 779, content: "Acme Corp deposit cheque"},
        {name: 606, content: "acme corp deposit cheque"}
       ]

案例2。)

输入:"亚马逊"或者"亚马逊"

预期产出:

       [
        {name: 789, content: "Amazon gift card"},
        {name: 646, content: "amazon gift card"}
       ]

案例3。)

输入:" Dunkin"或者" dunkin"或者" Dunkin-Donuts"或者" dunkin-donuts"或者" dunkin-Donuts"或者" Dunkin-donuts"或者"甜甜圈"或者"甜甜圈"

预期产出:

       [
        {name: 879, content: "Dunkin-Donuts"},
        {name: 656, content: "Dunkin Donuts"}
       ]

谢谢!任何帮助都将深表感谢。

1 个答案:

答案 0 :(得分:0)

$regex

您可以将$regexi标志一起使用以防止不区分大小写:

transactions.find( { content: { $regex: /acme/i } } )

$text

或者使用$text(为了获得更好的性能),首先在包含要搜索的文本的字段上创建text索引

transactions.createIndex( { content: "text" } )

然后:

transactions.find( { $text: { $search: "acme" } } )