@superhero/elastic

0.0.1 • Public • Published

An object modeling tool for elasticsearch.

Example

const
elastic = require('@superhero/elastic'),
type    = elastic.type,
schema  =
{
  created   : type.date,
  updated   : type.date,
  title     : type.text,
  body      : type.text,
  viewed    : type.integer,
  comments  :
  {
    ip      : type.ip,
    email   : type.keyword,
    avatar  : type.binary,
    location: type.geo_point,
    title   : type.text,
    body    : type.text,
    rating  : type.float,
    approved: type.boolean
  }
},
host  = 'localhost',
port  = 9200,
db    = elastic.db(host, port[, user, password, ssl=false]);

// Will reindex the index to reflect the defined schema, if the schema defined
// is different from what's already mapped.
// To prevent reindexing; use the last argument. If set to false, will throw an
// error if the mapping does not match what's already defined. Only creates the
// index if the index doesn't already exist.
// The "index-name" is optional an optional argument, if no index name is
// defined then the type name will be used.
db.index(['index-name',] 'blog', schema [, update=true], (error, index) =>
{
  // basic interface of the index, the interface can be extended
  // index.search(terms, cb);
  // index.remove(id, cb);
  // index.add(item, cb);
  // index.save(id, item, cb);
  // index.rest(method, uri, params, body, cb);
  // index.filter(map);
  // index.validate(map);

  // find by ...
  index.findByTitle         = (title, cb) => this.find({title}, cb);
  index.findByCommentTitle  = (title, cb) => this.find({comments:{title}}, cb);
  index.findCommentsByTitle = (title, cb) => this.find({title}, (error, result) => cb(error, result && [].concat(...result.map(item => item.comments))));

  // input filter
  index.filter =
  {
    title   : (value, action, cb) => cb(value.trim()),
    created : (value, action, cb) => cb(action == 'add'   ? Date.now()  : undefined),
    updated : (value, action, cb) => cb(action == 'save'  ? Date.now()  : undefined),
    comments: (value, action, cb) => cb([].isArray(value) ? value       : (item === undefined ? undefined : [value])),
  });

  // input validator
  index.validate =
  {
    comments:
    {
      email : (value, cb) => cb(value.test(/\S+@\S+\.\S+/))
    }
  });
});

Readme

Keywords

Package Sidebar

Install

npm i @superhero/elastic

Weekly Downloads

2

Version

0.0.1

License

MIT

Last publish

Collaborators

  • superhero