public
Last active

indextank with Node and Spore

  • Download Gist
indextank.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
// mkdir indextank
// wget https://github.com/SPORE/api-description/blob/master/services/indextank.json
// install node and npm
// npm install spore underscore futures
// edit baseUrl, password and index var
// node indextank.js
 
var baseUrl = 'http://xxx.api.indextank.com';
var password = 'xxx';
var index = 'test_spore';
 
var spore = require('spore');
var _ = require('underscore');
var futures = require('futures');
 
var client = spore.createClient(__dirname +'/indextank.json', {base_url: baseUrl});
 
// json middleware
client.enable(spore.middlewares.json());
// status middleware (throw error if http status is not expected)
client.enable(spore.middlewares.status());
// authentication middleware
client.enable(spore.middlewares.basic('', password));
 
function say(text) {
return function(next) {
console.log(text);
next();
};
}
 
function listIndexes() {
return function(next) {
client.list_indexes(function(err, result) {
if (err) throw err;
_(result.body).chain().keys().each(function(value) {console.log(' -> %s', value) });
next();
});
}
}
 
function createIndex(name) {
return function(next) {
console.log('create a new index %s', name);
client.create_index({name: name}, function(err, result) {
if (err) throw err;
next();
});
};
}
 
function getIndex(name) {
return function(next) {
console.log('get informations about index %s', name);
client.get_index({name : name}, function(err, result) {
if (err) throw err;
console.log('%s (size: %s)', name, result.body.size);
next();
});
};
}
 
function createDocuments(name) {
return function(next) {
var docs = [
{
docid : 'Perl',
fields : { version : '5.14.0'}
},
{
docid : 'Node',
fields : { version : 'v0.4.8'}
}
];
client.add_documents({name : name}, JSON.stringify(docs), function(err, result) {
if (err) throw err;
next();
});
}
}
function search(name, query) {
return function(next) {
client.search({name : name, q : query}, function(err, result) {
console.log('for search %s on %s, we got %d', query, name, result.body.matches);
_(result.body.results).chain().pluck('docid').each(function(value) {
console.log(value);
});
next();
});
}
}
 
futures.sequence()
.then(say('listing indexes'))
.then(listIndexes())
.then(createIndex(index))
.then(say('listing (again) indexes'))
.then(listIndexes())
.then(getIndex(index))
.then(say('create documents'))
.then(createDocuments(index))
.then(getIndex(index))
.then(search('demoIndex', 'guitar'));

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.