【问题标题】:How to implement search for bookname, isbn, and author?如何实现书名、isbn、作者搜索?
【发布时间】:2017-02-16 23:25:47
【问题描述】:

我正在为图书搜索应用程序开发 Node - MongoDb 后端。我正在存储图书信息,例如 ISBN、作者、书名、出版商、位置等。我实现了书名搜索,如下所示:

const bookTitle= new RegExp(escapeRegex(request.params.query), 'gi');

然后使用 .find 方法进行 {title: bookTitle} 搜索。

我想从高层次上了解如何使用户能够输入作者、isbn 或标题,并能够在 MongoDb 中搜索这些属性。

我正在考虑检查查询是否为 10 位数字,然后进行 isbn 搜索以查找该案例?我在正确的轨道上吗?

【问题讨论】:

  • 我想到的另一件事是创建另一个属性,我在其中存储 isbn + ' ' + authors + ' ' + title。这样我可以执行一次搜索。

标签: node.js mongodb mongoose


【解决方案1】:

当然,对此有多种解决方案。假设您想要执行 OR 查询(即返回查询词匹配 author OR title OR ISBN 的结果),您可以使用正确的索引和 the $or 运算符来执行此操作。

我可能会从一个集合开始,将这些字段中的每一个分开:

{
  "_id" : 7, 
  "title" : "coffee and cream", 
  "author" : "John Doe", 
  "isbn" : 12312318
}

db.articles.createIndex( { author : 1 } )
db.articles.createIndex( { isbn : 1 } )
db.articles.createIndex( { title: "text" } )

您需要在每个字段上添加索引...看看text 索引类型和$text queries 这对title 字段很有帮助(注意,您只能每个集合使用 一个 $text 索引)。还请阅读 indexes work with $regex queries 如何对查询 author 有用。

当您获得查询词时,只需查询所有字段。然后,$or 查询将返回与这些字段中的任何一个匹配的结果

获取example in the $text documentation 并针对此解决方案对其进行修改...假设以下记录:

{ "_id" : 1, "subject" : "coffee", "author" : "xyz", "views" : 50, "isbn" : 12312312 }
{ "_id" : 2, "subject" : "Coffee Shopping", "author" : "efg", "views" : 5, "isbn" : 12312313 }
{ "_id" : 3, "subject" : "Baking a cake", "author" : "abc", "views" : 90, "isbn" : 12312314 }
{ "_id" : 4, "subject" : "baking", "author" : "xyz", "views" : 100, "isbn" : 12312315 }
{ "_id" : 5, "subject" : "Café Con Leche", "author" : "abc", "views" : 200, "isbn" : 12312316 }
{ "_id" : 6, "subject" : "Сырники", "author" : "jkl", "views" : 80, "isbn" : 12312317 }
{ "_id" : 7, "subject" : "coffee and cream", "author" : "efg", "views" : 10, "isbn" : 12312318 }
{ "_id" : 8, "subject" : "Cafe con Leche", "author" : "xyz", "views" : 10, "isbn" : 12312319 }
{ "_id" : 10, "subject" : "The Coffee Book: Anatomy of an Industry from Crop to the Last Drop", "author" : "Nina Luttinger", "isbn" : 1595580603 }

搜索作者:

> db.articles.find({ $or: [ 
     { $text: { $search: "lutt" } }, 
     { isbn: 'lutt' }, 
     { author: /lutt/i } 
  ] } )
{ "_id" : 10, "subject" : "The Coffee Book: Anatomy of an Industry from Crop to the Last Drop", "author" : "Nina Luttinger", "isbn" : 1595580603 }

搜索标题:

> db.articles.find({ $or: [ 
     { $text: { $search: "cafe" } }, 
     { isbn: 'cafe' }, 
     { author: /cafe/i } 
  ] } )
{ "_id" : 5, "subject" : "Café Con Leche", "author" : "abc", "views" : 200, "isbn" : 12312316 }
{ "_id" : 8, "subject" : "Cafe con Leche", "author" : "xyz", "views" : 10, "isbn" : 12312319 }

您还可以在服务器端执行一些基本逻辑来检查查询词是否为整数,然后从搜索中删除 isbn 查询运算符或查询 only isbn if查询一个整数。这意味着上述查询将根本不包含$or 查询列表中的isbn 字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 2010-09-07
    相关资源
    最近更新 更多