要将两个索引联表查询,可以使用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中实现联表查询的方法,具体选择哪种方法取决于你的数据结构和查询需求

ES内两个索引分别是门店索引、商品索引关联字段商户ID现在将两个索引联表查询。

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

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