MongoDB 3.4.5:连字符减号不适用于$text搜索

MongoDB 3.4.5:连字符减号不适用于$text搜索,mongodb,search,Mongodb,Search,我使用MongoDB,版本3.4.5,并试图排除带有-(减号)的术语。 不管出于什么原因,它都不起作用。 以下是我的尝试: db.Product.find() { "_id" : ObjectId("59cbfcd01889a9fd89a3565c"), "name" : "Produkt Neu", ... { "_id" : ObjectId("59cc7d941889a4f4c2f43b14"), "name" : "Produkt2", ... db.Product.f

我使用MongoDB,版本3.4.5,并试图排除带有-(减号)的术语。 不管出于什么原因,它都不起作用。 以下是我的尝试:

db.Product.find()
    { "_id" : ObjectId("59cbfcd01889a9fd89a3565c"), "name" : "Produkt Neu", ...
    { "_id" : ObjectId("59cc7d941889a4f4c2f43b14"), "name" : "Produkt2", ...

db.Product.find( { $text: { $search: 'Produkt -Neu' } } );

db.Product.find( { $text: { $search: "Produkt -Neu" } } );

db.Product.find( { $text: { $search: "Produkt2" } } );
    { "_id" : ObjectId("59cc7d941889a4f4c2f43b14"), "name" : "Produkt2", ...

db.Product.dropIndexes()

db.Product.createIndex({ name: "text" })
    {
        "nIndexesWas" : 2,
        "msg" : "non-_id indexes dropped for collection",
        "ok" : 1
    }

    {
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
    }

db.Product.find( { $text: { $search: "Produkt -Neu" } } );

db.Product.find( { $text: { $search: "Produkt Neu" } } );
    { "_id" : ObjectId("59cbfcd01889a9fd89a3565c"), "name" : "Produkt Neu", ...

有人知道我必须做什么才能让它与-(减)一起工作吗?

我创建了一个集合:
产品
包含以下文档

{
    "_id" : ObjectId("59d0ada3c26584cd8b79fc51"),
    "name" : "Produkt Neu"
}

{
    "_id" : ObjectId("59d0adafc26584cd8b79fc54"),
    "name" : "Produkt2"
}
。。。我在这个集合上声明了一个文本索引,如下所示:

db.Product.createIndex({ name: "text" })
我运行了以下查询,忠实地再现了您问题中描述的情况:

// returns one document since there is one document 
// which has the text indexed value: "Produkt Neu"
db.Product.find( { $text: { $search: "Produkt Neu" } } );

// returns no documents since there is no document 
// which has the text indexed value: "Produkt2"
db.Product.find( { $text: { $search: "Produkt -Neu" } } )
我想你是在期待这个问题

db.Product.find( { $text: { $search: "Produkt -Neu" } } )
db.Product.find( { $text: { $search: "Produkt -Neu" } } );
。。。返回第二个文档,理由是排除
Neu
应允许对具有
name=Produkt2
的文档进行匹配,但这不是MongoDB
$text
搜索的工作方式。MongoDB
$text
搜索不支持部分匹配,因此搜索词
Produkt-Neu
(其计算结果为
Produkt
)将不匹配
Produkt2
。为了验证这一点,我运行了以下查询:

db.Product.find( { $text: { $search: "Produkt2 -Neu" } } ) 
此查询返回第二个文档(即带有
name=Produkt2
)证明连字符减号(
-
)成功地否定了术语:
Neu

在旁注上;MongoDB文本索引确实支持语言词干分析,为了验证这种行为,我添加了以下文档

{
    "_id" : ObjectId("59d0b2b4c26584cd8b79fd7c"),
    "name" : "Produkts"
}
…然后运行此查询

db.Product.find( { $text: { $search: "Produkt -Neu" } } )
db.Product.find( { $text: { $search: "Produkt -Neu" } } );
此查询返回带有
name=Produkts
的文档,因为
Product
Produkts
的词干

总之,
$text
搜索将查找匹配项,其中每个搜索项都有(a)文本索引中整个世界的匹配项,或(b)文本索引中整个单词的识别词干。注意:也有短语匹配,但与问题中的示例无关。使用连字符减号可以更改搜索词,但不会更改搜索词的计算方式

更多细节,MongoDB还有一个与此相关的未决问题

如果您确实需要支持部分匹配,那么您可能希望放弃文本索引,而使用
$regex
操作符。尽管值得注意的是,
$regex
操作符的索引覆盖率可能不是您所期望的,但简要的总结是:如果您的搜索值是锚定的(即
Produk
,而不是
rodukt
),那么MongoDB可以使用索引,但否则它不能使用