首页 > 解决方案 > elasticsearch 和 typescript - 将结果绑定到模型

问题描述

我想让我的 elasticsearch api 尽可能接近我的模型。我想在客户端和服务器中享受强类型的好处。

我有一个客户模型:

export interface CustomerBody{
    name?: string;
}

export class CustomerModel implements IElModel<CustomerBody>{
    readonly index: string = "db";
    readonly type: string = "customer";
    id: string;
    body: CustomerBody = {}
}

保存此文档后,我运行一个查询,该查询具有不同的字段映射(与 mongodb 不同)。

数据库的结果是:

    "hits": [
      {
        "_index": "db",
        "_type": "customer",
        "_id": "pVM963UBtjK7RM81ZgIx",
        "_score": 1,
        "_source": {
          "name": "test"
        }
      },
      {
        "_index": "db",
        "_type": "customer",
        "_id": "p1NB63UBtjK7RM81kQIv",
        "_score": 1,
        "_source": {
          "name": "test3111111"
        }
      }
    ]

使用 nodejs 驱动程序,如何将此结果绑定到CustomerModel[]
如果我设法做到这一点,我的大部分逻辑将是强类型的。

谢谢

标签: typescriptelasticsearch

解决方案


我自己解决了类似的情况。我的解决方案是将 hits 数组映射到我的界面中,在您的情况下是一个类。

const models: CustomerModel[] = hits.map(hit => {
  const customer = new CustomerModel();
  customer.id = hit._id;
  customer.body = hit._source;

  return customer;
});

推荐阅读