3

一般来说,我对 CouchDB、Map/Reduce 和 NoSQL 还是很陌生。

我希望你们能指导我如何在我的 Node.js/CouchDB 应用程序上实现非常基本的搜索。

我正在寻找在 CouchDB 文档中搜索某些文本元素。

我在沙发上的大部分文件都采用下面提到的类似格式:

{
    "_id": "b001729a2c5cf4100ea50a71ec04e20b",
    "_rev": "1-8928ea122d80fd5c1da1c22dfc6ce46e",
    "Approved To Publish": "false",
    "Article Body": "has retained the Carbon Trust Standard for energy and carbon management.Following a demanding audit process that took place in December 2012, was awarded recertification for the Carbon Trust Standard.This certificate is a mark of excellence in recognition of how well we measure, manage and reduce our carbon emissions.",
    "Headline": "Delight retains Carbon Trust Standard"
}

我的搜索键将是例如“碳信托”、“排放”、“卓越认可”等。

我所拥有的是一个临时映射函数,我在 POST 请求中的 Node.js 应用程序的请求正文中使用它,但我确信它不是正确的方法,我希望它是 CouchDB 中的存储视图.

我的地图功能:

function (doc) {
    if ('Headline' in doc) {
        if (doc['Article Body'].search(/" + req.body.jsonValue  + "/i) !== -1
            || doc.Headline.search(/" + req.body.jsonValue + "/i) !== -1) {
            var key = doc.Headline,
                value = doc;
            emit(key, value);
        }
    }
}

请让我知道我需要做些什么来改进我的方法,或者如果事情不清楚,请告诉我。

问候

4

2 回答 2

2

列表函数可以访问查询字符串值,因此您只需添加一个与视图一起使用的值。

地图功能

function (doc) {
    if ("Headline" in doc) {
        emit(doc.Headline, doc);
    }
}

列表功能

function (head, req) {
    var rows = [],
        regex = new RegExp(req.query.search, "i"), // use the querystring param to create the RegExp object
        row;

    while (row = getRow()) {
        if (row.value.Headline.search(regex) > -1 || row.value["Article Body"].search(regex)) {
            rows.push(row);
        }
    }

    // I'm just mocking up what a view's output would look like (not required)
    send(JSON.stringify({
        total_rows: rows.length,
        offset: 0,
        rows: rows
    }));
}

当然,您可以修改 list 函数以分块发出数据,而不是一次发出所有数据,但这应该让您了解这样的解决方案是什么样的。

于 2013-05-20T13:56:35.160 回答
0

相反,您可以构建一个视图,其中键是关键字(或任何单词),值是_ids。

缺点是这个视图可能会变得非常大。CouchDB 专家可能对我认为的典型问题有更好的解决方案。

天真的例子1

function(doc) {
    if ('Headline' in doc) {
        for (key in doc.Headline.split(' ')) {
            emit(key, doc._id)
        }
    }
    if ('Article Body' in doc) {
        for (key in doc['Article Body'].split(' ')) {
            emit(key, doc._id)
        }
    }
}

然后你会用/app/_design/app/_view/search?key="keyword"例如查询它。

1:你实际上需要规范化大小写、删除标点符号、常用词如atheof等等……</sub>

于 2013-05-19T19:56:58.060 回答