(#63) - searching through deep arrays

* searching through deep arrays
nnarhinen's implementation with nolanlawson's requested changes

* Unnecessary break removed
This commit is contained in:
spicemix 2017-02-22 08:23:36 -08:00 committed by Nolan Lawson
parent 66eed68e7c
commit 71704536de
4 changed files with 87 additions and 2 deletions

View File

@ -131,7 +131,7 @@ pouch.search({
### Document structure
Your document fields can be strings or arrays of strings. Use dots to separate deeply nested fields.
Your document fields can be strings or arrays of strings. Use dots to separate deeply nested fields. Searching deeply inside arrays is supported.
```js
var doc = {

View File

@ -40,7 +40,11 @@ function getText(fieldBoost, doc) {
} else { // "Enhance."
text = doc;
for (var i = 0, len = fieldBoost.deepField.length; i < len; i++) {
text = text && text[fieldBoost.deepField[i]];
if (Array.isArray(text)) {
text = text.map(handleNestedObjectArrayItem(fieldBoost, fieldBoost.deepField.slice(i)));
} else {
text = text && text[fieldBoost.deepField[i]];
}
}
}
if (text) {
@ -53,6 +57,14 @@ function getText(fieldBoost, doc) {
return text;
}
function handleNestedObjectArrayItem(fieldBoost, deepField) {
return function (one) {
return getText(utils.extend({}, fieldBoost, {
deepField: deepField
}), one);
};
}
// map function that gets passed to map/reduce
// emits two types of key/values - one for each token
// and one for the field-len-norm

60
test/docs/test-docs-9.js Normal file
View File

@ -0,0 +1,60 @@
'use strict';
var docs = [
{
_id: '1',
list: ['much', 'text', 'goes', 'in this array, you see']
},
{
_id: '2',
nested: {
array: [{
aField: 'something'
}]
}
},
{
_id: '3',
aNumber : 1
},
{
_id: '4',
invalid: null
},
{
_id: '5',
invalid: {}
},
{
_id: '7',
nested: {
foo: null
}
},
{
_id: '8',
nested: {
array: null
}
},
{
_id: '9',
nested: {
array: []
}
},
{
_id: '10',
nested: {
array: [{
aField: 'something else'
},{
aField: 'something different'
},{
aField: 'foobar'
}]
}
}
];
module.exports = docs;

View File

@ -44,6 +44,7 @@ var docs5 = require('./docs/test-docs-5');
var docs6 = require('./docs/test-docs-6');
var docs7 = require('./docs/test-docs-7');
var docs8 = require('./docs/test-docs-8');
var docs9 = require('./docs/test-docs-9');
function tests(dbName, dbType) {
@ -564,6 +565,18 @@ function tests(dbName, dbType) {
ids.should.deep.equal(['2']);
});
});
it('allows searching from an array of nested objects', function () {
return db.bulkDocs({docs: docs9}).then(function () {
var opts = {
fields: ['nested.array.aField'],
query: 'something'
};
return db.search(opts);
}).then(function (res) {
var ids = res.rows.map(function (x) { return x.id; }).sort().reverse();
ids.should.deep.equal(['2', '10']);
});
});
it('allows searching string arrays', function () {
return db.bulkDocs({docs: docs5}).then(function () {
var opts = {