在Elasticsearch中,可以使用关联字段(join field)来实现两个索引的关联查询。以下是一个示例:

假设有两个索引,一个是"stores",包含门店信息,另一个是"products",包含商品信息。两个索引都有一个字段"merchant_id",用于关联商户。

首先,需要在创建索引时定义关联字段类型,以便进行关联查询。在创建"stores"索引时,可以定义一个关联字段类型,如下所示:

PUT stores
{
  "mappings": {
    "properties": {
      "merchant_id": {
        "type": "join",
        "relations": {
          "merchant": "product"
        }
      },
      // 其他字段
    }
  }
}

在创建"products"索引时,也需要定义一个关联字段类型,如下所示:

PUT products
{
  "mappings": {
    "properties": {
      "merchant_id": {
        "type": "join",
        "relations": {
          "product": "merchant"
        }
      },
      // 其他字段
    }
  }
}

接下来,可以将门店和商品的数据索引到对应的索引中。假设有以下数据:

// 门店数据
PUT stores/_doc/1
{
  "merchant_id": {
    "name": "merchant"
  },
  "store_name": "Store 1",
  // 其他字段
}

// 商品数据
PUT products/_doc/1
{
  "merchant_id": {
    "name": "product",
    "parent": "1"
  },
  "product_name": "Product 1",
  // 其他字段
}

现在,可以执行关联查询。例如,通过门店ID查询关联的商品:

GET stores/_search
{
  "query": {
    "term": {
      "_id": "1"
    }
  },
  "size": 1,
  "_source": ["store_name"],
  "stored_fields": [],
  "collapse": {
    "field": "merchant_id"
  }
}

该查询将返回门店名称以及关联的商品信息。

注意:关联查询在Elasticsearch中是相对较新的功能,需要使用适当的版本才能支持

在Elasticsearch内有门店索引、商品索引把两个索引用商户id关联联表查询

原文地址: https://www.cveoy.top/t/topic/h3VF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录