为了按文本搜索mongo数据库中的项目,我需要根据documentation创建一个索引。
以下代码创建了这个索引:
index is Index {iColl = "note", iKey = [ text: 1], iName = "text_1", iUnique = False, iDropDups = False}
为什么代码会出现此错误?
*** Exception: expected "results" in [ ok: 0.0, errmsg: "no text index for: db.note"]
更新
我使用以下更新的代码得到了同样的错误。我改变的是现在使用createIndex
。
let order = [(fieldToText TextField) =: (1 :: Int32)]
docIndex = index (docTypeToText docType) order
actionResult <- run pipe dbName $ createIndex docIndex
case actionResult of
Left failure -> do putStrLn $ show failure
return []
Right () -> do
putStrLn $ "index is " ++ show docIndex
run pipe dbName $ ensureIndex docIndex
mDoc <- run pipe dbName $ runCommand
[pack "text" =: (docTypeToText docType),
pack "search" =: (pack $ unwords keywords),
pack "filter" =: (selector $ selection query)]
case mDoc of
Left failure -> do putStrLn $ show failure
return []
Right doc -> let Array results = valueAt (pack "results") doc
ds = [d | Doc d <- results]
in return ds
更新请参阅下面的评论。
答案 0 :(得分:2)
我的猜测是:在开发Haskell驱动程序时,MongoDB根本不支持全文索引。因此,使用当前版本的驱动程序创建"text"
索引是不可能的。
更新1 :第二个想法,您可以创建一个"text"
索引,将文档插入"system.indexes"
,就像驱动程序中的done一样。< / p>
更新2 :使用createIndex
无济于事,因为MongoDB doesn't allow将"text"
传递为iKey
。这是一种似乎有效的方法:
createTextIndex :: Collection -> String -> [Label] -> Action IO ()
createTextIndex col name keys = do
db <- thisDatabase
let doc = [ "ns" =: db <.> col
, "key" =: [key =: ("text" :: String) | key <- keys]
, "name" =: name
]
insert_ "system.indexes" doc
search :: Collection -> String -> Document -> Action IO Document
search col term filter = runCommand [ "text" =: col
, "search" =: term
, "filter" =: filter
]
main :: IO ()
main = do
pipe <- runIOE $ connect host
res <- access pipe master "test" $ do
createTextIndex "foo" "foo-index" ["bar"]
search "foo" "some-keyword" []
print res
where
host = Host "localhost" $ UnixSocket "/tmp/mongodb-27017.sock"