Permalink
Browse files

Slightly better api. Query method and add with delete stub. This is s…

…etup to allow for inheritence for indexing and such, not sure that's the best approach.

Signed-off-by: Nick Campbell <nicholas.j.campbell@gmail.com>
  • Loading branch information...
1 parent 4d31aff commit 3fbc0d49ebc20efd556ff8e578e44ebed191a622 @ncb000gt committed Mar 2, 2011
Showing with 66 additions and 7 deletions.
  1. +66 −7 lib/elasticsearch.js
View
@@ -31,36 +31,95 @@ function ElasticSearch(args) {
module.exports = ElasticSearch;
-ElasticSearch.prototype.query = function(opts, cb) {
+ElasticSearch.prototype.add = function(opts, doc, cb) {
var def = {
host: this.config.host,
port: this.config.port,
- method: 'POST',
- path: '/' + this.config.index + '/_search?pretty=true'
+ method: ((opts.id)?'PUT':'POST'),
+ path: '/' + this.config.index + '/' + opts.type + '/' + (opts.id || '')
};
var query = {};
if (opts.query) {
- query = opts.query;
+ query = {query: opts.query};
delete opts.query;
}
- var _config = mapConfig(def, opts);
+ this._add(mapConfig(def, opts), query, cb);
+}
+
+ElasticSearch.prototype._add = function(opts, doc, cb) {
+ var req = http.request(opts, function(res) {
+ var chunks = [],
+ length = 0;
+ res.on('data', function(chunk) {
+ chunks.push(chunk);
+ length += chunk.length; //can't reliably use headers
+ });
+ res.on('error', cb);
+ res.on('end', function() {
+ var buf = new Buffer(length),
+ total = 0;
+ chunks.forEach(function chunk_cb(chunk) {
+ chunk.copy(buf, total, 0);
+ total += buf.length;
+ });
+
+ if (cb) {
+ cb(null, buf);
+ }
+ });
+ });
+
+ req.write(JSON.stringify(doc));
+ req.end();
+}
+
+ElasticSearch.prototype.delete = function(opts, cb) {
+}
+
+ElasticSearch.prototype._delete = function(opts, cb) {
+}
+
+ElasticSearch.prototype.query = function(opts, query, cb) {
+ var def = {
+ host: this.config.host,
+ port: this.config.port,
+ method: 'POST',
+ noend: true,
+ path: '/' + this.config.index + '/_search'
+ };
- var req = http.request(_config, function(res) {
+ this._query(mapConfig(def, opts), query, cb);
+}
+
+ElasticSearch.prototype.queryAll = function(opts, query, cb) {
+ var def = {
+ host: this.config.host,
+ port: this.config.port,
+ method: 'POST',
+ path: '/_search'
+ };
+
+ this._query(mapConfig(def, opts), query, cb);
+}
+
+ElasticSearch.prototype._query = function(opts, query, cb) {
+ var req = http.request(opts, function(res) {
var chunks = [],
length = 0;
res.on('data', function(chunk) {
chunks.push(chunk);
length += chunk.length; //can't reliably use headers
});
+ res.on('error', cb);
res.on('end', function() {
var buf = new Buffer(length),
total = 0;
chunks.forEach(function chunk_cb(chunk) {
chunk.copy(buf, total, 0);
total += buf.length;
});
- console.log('data: ' + buf.toString());
+
if (cb) {
cb(null, buf);
}

0 comments on commit 3fbc0d4

Please sign in to comment.