简体   繁体   English

如何检索包含搜索词的子字符串的DBObject?

[英]How can I retrieve DBObjects that contains a substring of a search-word?

I am using MongoDB with Java Driver ( http://tinyurl.com/dyjxz8k ). 我正在将MongoDB与Java驱动程序( http://tinyurl.com/dyjxz8k )一起使用。 In my application I want it to be possible to give results that contains a substring of the users search-term. 在我的应用程序中,我希望能够给出包含用户搜索项的子字符串的结果。 The method looks like this: 该方法如下所示:

*searchlabel = the name of a field *searchTerm = the users searchword * searchlabel =字段名称* searchTerm =用户的搜索词

 private void dbSearch(String searchlabel, String searchTerm){
    if(searchTerm != null && (searchTerm.length() > 0)){

        DBCollection coll = db.getCollection("MediaCollection");
        BasicDBObject query = new BasicDBObject(searchlabel, searchTerm);
        DBCursor cursor = coll.find();
        cursor = coll.find(query);

        try {
            while(cursor.hasNext()) {
                System.out.println(cursor.next());
                //view.showResult(cursor.next());
            }
        } finally {
            cursor.close();
        }

    }
}

Does anybody have any idea about how I can solve this? 有人对我该如何解决有任何想法吗? Thanks in advance =) And a small additional question: How can I handle the DBObjects according to presentation in (a JLabel in) view? 预先感谢=)还有一个小问题:如何根据(JLabel in)视图中的表示处理DBObject?

For text-searching in Mongo, there are two options: 对于在Mongo中进行文本搜索,有两种选择:

  • $regex operator - however unless you have a simple prefix regexp, queries won't use an index, and will result in a full scan, which usually is slow $regex运算符 -但是,除非您有一个简单的前缀regexp,否则查询将不使用索引,并且将导致完全扫描,这通常很慢
  • In Mongo 2.4, a new text index has been introduced. 在Mongo 2.4中,引入了新的文本索引 A text query will split your query into words, and do an or-search for documents including any of the words. text查询会将您的查询分解为单词,然后对包含任何单词的文档进行“或”搜索。 Text indexes also eliminate some stop-words and have simple stemming for some languages (see the docs ). 文本索引还消除了一些停用词,并且对某些语言具有简单的词干(请参阅docs )。

If you are looking for a more advanced full-text search engine, with more powerful tokenising, stemming, autocomplete etc., maybe a better fit would be eg ElasticSearch . 如果您正在寻找更高级的全文本搜索引擎,并具有更强大的标记,词干,自动完成等功能,那么更好的选择是,例如ElasticSearch

I use this method in the mongo console to search with a regular expression in JavaScript: 我在mongo控制台中使用此方法在JavaScript中使用正则表达式进行搜索:

// My name to search for
var searchWord = "alex";

// Construct a query with a simple /^alex$/i regex
var query = {};
query.animalName = new RegExp("^"+searchWord+"$","i");

// Perform find operation
var lionsNamedAlex = db.lions.find(query);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM