要将两个索引联表查询,可以使用 Elasticsearch 的 Nested 类型或者 Parent-Child 关系。

  1. Nested 类型:将商品索引嵌套在门店索引中。在门店索引中,创建一个 nested 字段,用于存储商品信息。示例代码如下:
PUT stores
{
  "mappings": {
    "properties": {
      "store_id": {
        "type": "integer"
      },
      "merchant_id": {
        "type": "integer"
      },
      "products": {
        "type": "nested",
        "properties": {
          "product_id": {
            "type": "integer"
          },
          "product_name": {
            "type": "text"
          }
        }
      }
    }
  }
}

PUT products
{
  "mappings": {
    "properties": {
      "product_id": {
        "type": "integer"
      },
      "product_name": {
        "type": "text"
      },
      "merchant_id": {
        "type": "integer"
      }
    }
  }
}

通过 Nested 类型,可以在门店索引中嵌套存储商品信息。然后,可以使用 Nested 查询来联表查询门店和商品,例如:

GET stores/_search
{
  "query": {
    "nested": {
      "path": "products",
      "query": {
        "match": {
          "products.product_name": "iPhone"
        }
      }
    }
  }
}
  1. Parent-Child 关系:将门店索引作为父索引,商品索引作为子索引。在创建商品索引时,使用 "_parent" 字段来指定父文档(门店索引)。示例代码如下:
PUT stores
{
  "mappings": {
    "properties": {
      "store_id": {
        "type": "integer"
      },
      "merchant_id": {
        "type": "integer"
      }
    }
  }
}

PUT products
{
  "mappings": {
    "_parent": {
      "type": "stores"
    },
    "properties": {
      "product_id": {
        "type": "integer"
      },
      "product_name": {
        "type": "text"
      }
    }
  }
}

通过 Parent-Child 关系,可以在门店索引和商品索引之间建立关联。然后,可以使用 Has Child 查询或 Has Parent 查询来联表查询门店和商品,例如:

GET stores/_search
{
  "query": {
    "has_child": {
      "type": "products",
      "query": {
        "match": {
          "product_name": "iPhone"
        }
      }
    }
  }
}

以上是两种在 Elasticsearch 中实现联表查询的方法,具体选择哪种方法取决于你的数据结构和查询需求。

Elasticsearch 联表查询:门店和商品索引关联

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

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