2015-12-12 6 views
5

Java API for MongoDBを使用する際に問題があります。私はRobomongoを使用してクエリを作成しました:MongoDB Java API:全文検索

db.collection.find(
    {$text : {$search : "\"expression\" keyword"}}, 
    {score : {$meta : "textScore"}} 
).sort({score : {$meta : "textScore"}}) 

今私は、Java APIを使用して、同じクエリを作成したいと思います:

DBObject searchCommand = new BasicDBObject(
    "$text", new BasicDBObject("$search", "\"expression\" keyword") 
).append(
    "score", new BasicDBObject("'$meta'", "textScore") 
); 

DBObject sorting = new BasicDBObject(
    "score", new BasicDBObject("'$meta'", "textScore") 
); 

DBCursor result = collection.find(searchCommand).sort(sorting); 

問題は、このコードは動作しないということです。クエリ:

DBObject searchCommand = new BasicDBObject(
    "$text", new BasicDBObject("$search", "\"expression\" keyword") 
); 

が完全に動作します。 2番目の部分を追加すると、すべての結果が見えなくなります。さらに、この行:

DBCursor result = collection.find(searchCommand).sort(sorting); 

throws MongoException(BadValue不良ソート仕様)。 sort()メソッドの呼び出しを取り除くとExceptionは存在しませんが、まだ結果はありません( "score"を追加した場合)。

私はこの問題を解決しましたが、Springを使用しています。私は他のライブラリを使用したくありません。また、私はMongoDBの初心者です。あなたの助けと時間、歓声をありがとう。


更新。問題が解決しました。 findCommandがfind()の最初のパラメータとして渡されたクエリに「score」を追加するのは間違っています。

DBObject search = new BasicDBObject(
    "$text", new BasicDBObject("$search", "\"expression\" keyword") 
); 

DBObject project = new BasicDBObject(
    "score", new BasicDBObject("$meta", "textScore") 
); 

DBObject sorting = new BasicDBObject(
    "score", new BasicDBObject("$meta", "textScore") 
); 

DBCursor result = collection.find(search, project).sort(sorting); 

答えて

6

は、あなたがしようとしているものと、実際に親しま:次のように「スコア」のfind()メソッドの2番目のパラメータとして別のDBObjectをに渡す必要があります。

注は、

db.collection.find(
    {$text : {$search : "\"expression\" keyword"}}, 
    {score : {$meta : "textScore"}} 
).sort({score : {$meta : "textScore"}}) 
  • {$text : {$search : "\"expression\" keyword"}}からquery部分です。

  • {score : {$meta : "textScore"}} - はprojection部分です。あなたがJavaドライバを使用して実装しようとしたもので

DBObject searchCommand = new BasicDBObject(
    "$text", new BasicDBObject("$search", "\"expression\" keyword") 
).append(
    "score", new BasicDBObject("'$meta'", "textScore") 
); 

生産に終わるだろう、ネイティブクエリと同等ではありません

{$text:{$search:"\"expression\" keyword"},"score":{"meta":"textscore"}} 

宛てのprojection文もqueryの一部です。それは今queryないprojectionの一部となっているので、これは、scoreというフィールドを探して終わる

注意。

あなたは簡単に、あなたのDBObjectインスタンスを変更することができ、それprojectionパラメータの一部にするために、それが働くだろう:

DBObject findCommand = new BasicDBObject(
    "$text", new BasicDBObject("$search", "keyword") 
); 

DBObject projectCommand = new BasicDBObject(
    "score", new BasicDBObject("$meta", "textScore")); 

DBObject sortCommand = new BasicDBObject(
    "score", new BasicDBObject("$meta", "textScore") 
); 
DBCursor result = collection.find(
            findCommand ,projectCommand) 
            .sort(sortCommand); 
+1

はどうもありがとうございました:)私がいくつかの瞬間、あなたの前に私の問題を発見したようです応答。とにかく包括的な説明に感謝します。 – bargro