ES父子关系创建、新增、查询、更新、删除

父子文档的特点

1. 父/子文档是完全独立的。 2. 父文档更新不会影响子文档。 3. 子文档更新不会影响父文档或者其它子文档。

操作如下:

    创建索引
PUT auto_parts-whole-network-index
    创建别名
POST /_aliases
{
	"actions": [{
		"add": {
			"index": "auto_parts-whole-network-index",
			"alias": "auto_parts-whole-network-alias"
		}
	}]
}
    添加字段
PUT auto_parts-whole-network-index/_mapping/auto_parts-whole-network-type
{
	"properties": {
		"enterpriseId": {
			"type": "keyword"
		},
		"companyName": {
			"type": "keyword"
		}
	}
}
    新增数据
##添加父文本 ID:10000000001

PUT auto_parts-whole-network-index/_doc/10000000001
{
  "companyName": "企业名称",
  "enterprise_product": {
    "name": "enterprise" 
  }
}


##添加子文本,父文本ID:10000000001 子文本ID:20000000001
PUT auto_parts-whole-network-index/_doc/20000000001?routing=10000000001
{
  "productName": "商品",
  "enterprise_product": {
    "name": "product", 
    "parent": "10000000001" 
  }
}
    查询enterpriseId为空的数据(返回父文档及子文档10条)
POST auto_parts-whole-network-alias/_search
{
	"from": 0,
	"size": 10,
	"query": {
		"has_child": {
			"query": {
				"bool": {
					"must_not": {
						"exists": {
							"field": "enterpriseId"
						}
					},
					"adjust_pure_negative": true,
					"boost": 1
				}
			},
			"type": "product",
			"inner_hits": {
				"size": 10
			}
		}
	}
}
    根据企业ID查询(返回子数据)
POST auto_parts-whole-network-alias/_search
{
  "query": {
    "has_parent": {
      "parent_type": "enterprise",
      "query": {
        "term": {
          "enterpriseId": {
            "value": "236848"
          }
        }
      }
    }
  }
}
    查询enterpriseId为空的数据(返回所有文档)
POST auto_parts-whole-network-alias/_search
{
  "from": 0,
  "size": 10,
  "query": {
    "bool": {
      "must_not": {
        "exists": {
          "field": "enterpriseId"
        }
      },
      "adjust_pure_negative": true,
      "boost": 1
    }
  }
}
    根据条件删除数据
POST auto_parts-whole-network-alias/_delete_by_query
{
  "query": {
    "bool": {
      "must": [
       {
         "terms": {
           "pkid": ["23C3FE6C14DCC35C3D152461ED99FCB2"]
         }
       }
      ]
    }
  }
}
    根据条件更新数据
POST auto_parts-whole-network-index/_update_by_query
{
    "script": {
        "inline": "ctx._source[contactPhoneList]=13415155455;"
    },
    "query": {
        "bool": {
            "must": [
                {
                    "term": {
                        "pkid": "02C92154C3E5EA43054A3681DE938533"
                    }
                }
            ]
        }
    }
}
经验分享 程序员 微信小程序 职场和发展