Elasticsearch Javascript API增删改查

本文涉及的产品
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
简介:

查询

根据索引、类型、id进行查询:

client.get({ 
     index:'myindex', 
     type:'mytype', 
     id:1 
},function(error, response){// ...});

根据某个查询条件,查询某个索引的所有数据

client.search({ 
     index:'myindex', 
     q:'title:test' 
},function(error, response){// ...});

复杂一点的查询:

client.search({ 
     index:'myindex', 
     body:{ 
         query:{ 
             match:{ 
                 title:'test' 
                } 
            }, 
         facets:{ 
             tags:{ 
                 terms:{ 
                     field:'tags' 
                    } 
                } 
            } 
        } 
},function(error, response){// ...});

新增

新增时,需要指定索引,类型,和id,还有保存的内容:

client.create({ 
     index:'myindex', 
     type:'mytype', 
     id:'1', 
     body:{ 
         title:'Test 1', 
         tags:['y','z'], 
         published:true, 
         published_at:'2013-01-01', counter:1 
    } 
},function(error, response){// ...});

删除

按照索引,类型和id删除:

client.delete({ 
     index:'myindex', 
     type:'mytype', 
     id:'1' 
},function(error, response){// ...});

修改

修改操作通常使用update方法:

client.update({ 
     index:'myindex', 
     type:'mytype', 
     id:'1', 
     body:{ 
        // put the partial document under the `doc` key 
         doc:{ 
             title:'Updated' 
            } 
     } 
},function(error, response){// ...})

一次性执行多个操作

ESClient也支持一次性执行多个操作:

client.mget({ 
     body:{ 
         docs:[ { 
            _index:'indexA', _type:'typeA', _id:'1' 
        },{
            _index:'indexB', _type:'typeB', _id:'1' 
        },{ 
            _index:'indexC', _type:'typeC', _id:'1' 
        }] 
    } 
},function(error, response){// ...});

也支持下面的风格:

client.mget({ 
     index:'myindex', 
     type:'mytype', 
     body:{ ids:[1,2,3]} 
},function(error, response){// ...});

类似的也可以同时执行多个查询:

client.msearch({ 
     body:[ 
     // match all query, on all indices and types 
        {}, 
        { query:{ match_all:{}}}, 
    // query_string query, on index/mytype 
    { 
        _index:'myindex', 
        _type:'mytype' 
    },{ 
        query:{ 
            query_string:{ query:'"Test 1"'} 
            } 
    }] 
});

扩展

通过上面基本API的使用,基本可以了解js端对ESclient的操作。当然也可以使用下面的变成风格调用方法:

es[method](params)
它类似
es.method(params,回调方法)

在kibana中的_doc_send_to_es.js,使用了如下的封装:

function (method, validateVersion, body, ignore) {
      // debugger;
      var doc = this;
      // straight assignment will causes undefined values
      var params = _.pick(this._state, ['id', 'type', 'index']);
      params.body = body;
      params.ignore = ignore || [409];

      if (validateVersion && params.id) {
        params.version = doc._getVersion();
      }
      // debugger;
      return es[method](params)
      .then(function (resp) {
        // debugger;
        if (resp.status === 409) throw new errors.VersionConflict(resp);

        doc._storeVersion(resp._version);
        doc.id(resp._id);

        var docFetchProm;
        if (method !== 'index') {
          docFetchProm = doc.fetch();
        } else {
          // we already know what the response will be
          docFetchProm = Promise.resolve({
            _id: resp._id,
            _index: params.index,
            _source: body,
            _type: params.type,
            _version: doc._getVersion(),
            found: true
          });
        }

        // notify pending request for this same document that we have updates
        docFetchProm.then(function (fetchResp) {
          // use the key to compair sources
          var key = doc._versionKey();
          

          // clear the queue and filter out the removed items, pushing the
          // unmatched ones back in.
          var respondTo = requestQueue.splice(0).filter(function (req) {
            var isDoc = req.source._getType() === 'doc';
            var keyMatches = isDoc && req.source._versionKey() === key;
            debugger;
            // put some request back into the queue
            if (!keyMatches) {
              requestQueue.push(req);
              return false;
            }

            return true;
          });

          return courierFetch.fakeFetchThese(respondTo, respondTo.map(function () {
            return _.cloneDeep(fetchResp);
          }));
        });

        return resp._id;
      })
      .catch(function (err) {
        // cast the error
        throw new errors.RequestFailure(err);
      });
    };

因此使用时,又变成了:

xxx.call(this, 'create', false, body, []);

一层一层封装了很多,但是只要慢慢屡清除,就知道怎么使用了。

本文转自博客园xingoo的博客,原文链接:Elasticsearch Javascript API增删改查,如需转载请自行联系原博主。


相关实践学习
使用阿里云Elasticsearch体验信息检索加速
通过创建登录阿里云Elasticsearch集群,使用DataWorks将MySQL数据同步至Elasticsearch,体验多条件检索效果,简单展示数据同步和信息检索加速的过程和操作。
ElasticSearch 入门精讲
ElasticSearch是一个开源的、基于Lucene的、分布式、高扩展、高实时的搜索与数据分析引擎。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr(也是基于Lucene)。 ElasticSearch的实现原理主要分为以下几个步骤: 用户将数据提交到Elastic Search 数据库中 通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据 当用户搜索数据时候,再根据权重将结果排名、打分 将返回结果呈现给用户 Elasticsearch可以用于搜索各种文档。它提供可扩展的搜索,具有接近实时的搜索,并支持多租户。
相关文章
|
1月前
|
JavaScript 前端开发 API
常用JavaScript 数组 API大全
常用JavaScript 数组 API大全
32 0
|
1月前
|
API
egg.js 24.2写第一个api接口
egg.js 24.2写第一个api接口
71 0
|
2月前
|
存储 API 索引
Elasticsearch Reroute API 的使用
Elasticsearch Reroute API 的使用
39 1
|
3月前
|
存储 JSON 自然语言处理
Elasticsearch 利用API进行搜索
Elasticsearch 利用API进行搜索
35 0
|
3月前
|
分布式计算 JavaScript 前端开发
JS中数组22种常用API总结,slice、splice、map、reduce、shift、filter、indexOf......
JS中数组22种常用API总结,slice、splice、map、reduce、shift、filter、indexOf......
|
2月前
|
Web App开发 JavaScript NoSQL
深入浅出:构建基于Node.js的RESTful API
在当今快速发展的互联网时代,RESTful API已成为前后端分离架构中不可或缺的一部分。本文旨在为初学者和中级开发人员提供一个清晰、简洁的指南,详细介绍如何使用Node.js构建一个高效、可维护的RESTful API。通过结合实际案例,本文将从API设计理念出发,深入讲解如何利用Express框架及MongoDB数据库实现API的增删改查功能,同时探讨如何通过JWT进行安全认证,确保数据传输的安全性。此外,文章还将简要介绍如何使用Swagger生成API文档,使得API的测试和维护更加便捷。无论你是希望提升现有项目的API设计,还是想从零开始构建一个新项目,本文都将为你提供一条清晰的道路
|
1月前
|
JavaScript 前端开发 API
JavaScript循环遍历常用的7种方法以及常用的数组 API
JavaScript循环遍历常用的7种方法以及常用的数组 API
34 0
|
1月前
|
Web App开发 JavaScript 前端开发
使用Node.js和Express构建RESTful API
使用Node.js和Express构建RESTful API
16 0
|
1月前
|
JavaScript 索引
js数组的增删改查,十二种方法(含代码)
js数组的增删改查,十二种方法(含代码)
|
2月前
|
NoSQL JavaScript 前端开发
深入浅出:使用Node.js和MongoDB构建RESTful API
在当今的软件开发领域,构建高效、可扩展的Web服务已成为开发者的重要任务之一。本文将引导读者通过现代JavaScript环境——Node.js,搭配流行的NoSQL数据库MongoDB,一步步构建一个RESTful API。不同于常规的摘要,我们将采用故事化的方式,通过一个虚构的应用“BookFinder”的开发旅程,带领读者理解API设计、数据库交互及安全性考量等关键知识点。无论你是前端工程师希望深化后端知识,还是后端新手寻求实践机会,本文都将提供你所需的指南和启示。