{"id":6386,"date":"2019-02-17T19:35:55","date_gmt":"2019-02-18T03:35:55","guid":{"rendered":"http:\/\/www.couchbase.com\/blog\/?p=6386"},"modified":"2025-06-13T17:22:10","modified_gmt":"2025-06-14T00:22:10","slug":"n1ql-query-with-self-referencing-hierarchy","status":"publish","type":"post","link":"https:\/\/www.couchbase.com\/blog\/es\/n1ql-query-with-self-referencing-hierarchy\/","title":{"rendered":"Consulta N1QL con Jerarqu\u00eda Auto-referenciada"},"content":{"rendered":"<p>Una construcci\u00f3n de datos que aparece a menudo en las aplicaciones empresariales es la estructura jer\u00e1rquica de datos. La jerarqu\u00eda captura la relaci\u00f3n padre-hijo que a menudo existe entre el mismo objeto. Por ejemplo, la estructura de una empresa refleja la l\u00ednea jer\u00e1rquica entre los empleados. La organizaci\u00f3n empresarial captura la relaci\u00f3n entre empresas matrices y filiales. Jerarqu\u00edas territoriales en Ventas. Libro de cuentas en aplicaciones financieras.<\/p>\n<p>Debido a la naturaleza de auto-referencia de la jerarqu\u00eda, la consulta de la estructura de manera eficiente junto con sus datos asociados puede ser un reto para RDBMS, en particular desde una perspectiva de rendimiento. En este art\u00edculo, hablar\u00e9 de c\u00f3mo los SGBDR tradicionales gestionan las consultas jer\u00e1rquicas. Los retos con los que tiene que lidiar, y c\u00f3mo este problema puede ser abordado de manera similar con Couchbase N1QL y Couchbase GSI.<\/p>\n<h2>Estructura jer\u00e1rquica en las aplicaciones<\/h2>\n<p>La principal raz\u00f3n para reunir la informaci\u00f3n en una estructura jer\u00e1rquica es mejorar la comprensi\u00f3n de la informaci\u00f3n. La estructura jer\u00e1rquica de la empresa est\u00e1 dise\u00f1ada no s\u00f3lo para ayudar a gestionar la organizaci\u00f3n, sino tambi\u00e9n para proporcionar una estructura que permita medir y optimizar la eficacia de cada grupo. En una gran organizaci\u00f3n, el rendimiento de las ventas suele evaluarse, no s\u00f3lo a nivel individual, sino a nivel de equipo de ventas. En resumen, las empresas organizan la informaci\u00f3n en una estructura jer\u00e1rquica para poder comprender mejor el rendimiento comercial. Para lograr ese objetivo, las empresas necesitan un medio eficaz para consultar los datos jer\u00e1rquicos.<\/p>\n<h3>Representaci\u00f3n de la jerarqu\u00eda de la empresa<\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-6402\" src=\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/2019\/02\/Screen-Shot-2019-02-17-at-7.33.47-PM.png\" alt=\"\" width=\"841\" height=\"428\" srcset=\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-17-at-7.33.47-PM.png 1676w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-17-at-7.33.47-PM-300x153.png 300w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-17-at-7.33.47-PM-1024x521.png 1024w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-17-at-7.33.47-PM-768x390.png 768w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-17-at-7.33.47-PM-1536x781.png 1536w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-17-at-7.33.47-PM-20x10.png 20w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-17-at-7.33.47-PM-1320x671.png 1320w\" sizes=\"auto, (max-width: 841px) 100vw, 841px\" \/><\/p>\n<p>Aunque el modelo de datos de la base de datos es capaz de capturar eficazmente la estructura jer\u00e1rquica, la dificultad surge cuando es necesario consultar los datos jer\u00e1rquicos y la informaci\u00f3n relacionada.<\/p>\n<p><span style=\"text-decoration: underline;\"><strong>Considere este requisito:\u00a0<\/strong><\/span><strong>Obtenga el valor total de los pedidos de venta de todos los representantes de ventas que dependen de ThomasH-Vicepresidente de Ventas.<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-6397\" src=\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/2019\/02\/Screen-Shot-2019-02-16-at-6.16.28-PM.png\" alt=\"\" width=\"879\" height=\"356\" srcset=\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-16-at-6.16.28-PM.png 2098w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-16-at-6.16.28-PM-300x122.png 300w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-16-at-6.16.28-PM-1024x415.png 1024w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-16-at-6.16.28-PM-768x311.png 768w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-16-at-6.16.28-PM-1536x622.png 1536w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-16-at-6.16.28-PM-2048x830.png 2048w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-16-at-6.16.28-PM-20x8.png 20w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-16-at-6.16.28-PM-1320x535.png 1320w\" sizes=\"auto, (max-width: 879px) 100vw, 879px\" \/><\/p>\n<p>Aunque el modelo de datos es relativamente sencillo. La naturaleza jer\u00e1rquica de la organizaci\u00f3n de ventas sugiere una estructura din\u00e1mica inherente en la jerarqu\u00eda de informes. AjayW, que dirige el territorio de la Regi\u00f3n1, tambi\u00e9n gestiona directamente a los miembros del equipo de ventas. Mientras que, en la Regi\u00f3n2, Liz L dirige a dos Gerentes, que a su vez dirigen al equipo de ventas. Esto es t\u00edpico en la mayor\u00eda de las jerarqu\u00edas de datos de aplicaci\u00f3n.<\/p>\n<h4>Enfoque RDMBS<\/h4>\n<p>Para consultar datos jer\u00e1rquicos, los RDBMS m\u00e1s consolidados como Oracle y SQLSever proporcionan la construcci\u00f3n CONNECT BY \/ START WITH para permitir que una sola consulta recorra recursivamente la estructura de empleados de la jerarqu\u00eda.<\/p>\n<pre class=\"lang:tsql decode:true\" title=\"RDBMS - Pedidos de venta generados por los miembros que dependen de ThomasH-VP Ventas\">Query: Sales orders generated by members who report up to ThomasH-Sales VP&lt;\/strong&gt;&lt;\/span&gt;\r\n\r\nSELECT e.EmpID, e.Name, e.ManagerID, sum(o.orderVal)\r\n   FROM employee e\r\n   INNER JOIN sales_order o ON o.EmpID = o.EmpId\r\n   START WITH EmpID = 101\r\n   CONNECT BY PRIOR EmpID = ManagerID\r\n   GROUP BY  e.EmpID, e.Name, e.ManagerID;\r\n\r\n<\/pre>\n<p>Aunque la consulta anterior puede parecer sencilla, el rendimiento de la consulta es dif\u00edcil de mejorar con \u00edndices debido a la naturaleza recursiva de la implementaci\u00f3n de CONNECT BY. Por este motivo, esta t\u00e9cnica no es popular en el desarrollo de aplicaciones para sistemas con un gran volumen de datos. En su lugar, las aplicaciones empresariales conf\u00edan en una estructura de objetos previamente aplanada para obtener un rendimiento de consulta m\u00e1s predecible. La t\u00e9cnica de jerarqu\u00eda aplanada se describe en la secci\u00f3n de Couchbase N1QL m\u00e1s abajo.<\/p>\n<h4>Couchbase N1QL<\/h4>\n<p>Para obtener el mejor rendimiento de consulta, las aplicaciones N1QL deben utilizar la estructura jer\u00e1rquica aplanada. El enfoque proporciona un rendimiento m\u00e1s predecible, as\u00ed como un mejor aprovechamiento de Couchbase GSI. El diagrama de abajo muestra un ejemplo de la transformaci\u00f3n flattening de una estructura jer\u00e1rquica autorreferenciada, como el objeto empleado. Tambi\u00e9n incluyo un fragmento de c\u00f3digo python que puedes usar para aplanar la estructura jer\u00e1rquica.  El <strong><em>aplanar_jerarqu\u00eda<\/em><\/strong> toma un objeto JSON jer\u00e1rquico auto-referenciado y genera dos nuevos objetos en el mismo espacio de claves pero con diferentes valores de tipo<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-6420\" src=\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM.png\" alt=\"\" width=\"948\" height=\"416\" srcset=\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM.png 1774w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM-300x132.png 300w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM-1024x449.png 1024w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM-768x337.png 768w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM-1536x674.png 1536w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM-20x9.png 20w, https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM-1320x579.png 1320w\" sizes=\"auto, (max-width: 948px) 100vw, 948px\" \/><\/p>\n<ul>\n<li>En <em>objeto_hier<\/em> funciona con consultas BI agregadas, en las que los resultados de la consulta se pueden acumular para cada nivel.<\/li>\n<li>En <em>objeto_nivel_superior<\/em> proporciona el mismo resultado que la cl\u00e1usula CONNECT BY\/START WITH, que devuelve todos los objetos hijo de un nodo determinado. Este es el objeto que utilizaremos en nuestra consulta N1QL para proporcionar la soluci\u00f3n de consulta.<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\" title=\"Consulta: Pedidos de ventas generados por miembros que dependen de ThomasH-VP Ventas SELECT e.EmpID, e.Name, e.ManagerID, sum(o.orderVal) FROM employee e INNER JOIN sales_order o ON o.EmpID = o.EmpId START WITH EmpID = 101 CONNECT BY PRIOR EmpID = ManagerID GROUP BY e.EmpID, e.Name, e.ManagerID;\">N1QL Query: Sales orders generated by members who report up to ThomasH-Sales VP\r\n\r\n\r\nSELECT e.id,sum(a.value)\r\nFROM crm a\r\nINNER JOIN (\r\n      SELECT uhl.id FROM crm uhl WHERE uhl.type ='_employee_hier_level'\r\n     AND uhl.parent='101') e USE HASH(probe) ON a.owner = e.id\r\nWHERE a.type='sales_order'\r\nGROUP BY e.id<\/pre>\n<p>\u00cdndice GS recomendado:<\/p>\n<pre class=\"lang:default decode:true\">CREATE INDEX `crm_employee_hier_level` ON `crm`(`parent`) WHERE (`type` = \"_employee_hier_level\")<\/pre>\n<p>Notas:<\/p>\n<ol>\n<li>La consulta principal recupera todos los pedidos de cliente de la base de datos <code>crm<\/code>\u00a0cubo con tipo valor = 'pedido'<\/li>\n<li>La consulta realiza un HASH JOIN con otra consulta (funci\u00f3n de N1QL 6.5) que recupera todos los ID de los empleados que dependen del usuario101, es decir, ThomasH-SalesVP<\/li>\n<li>Los \u00edndices de cobertura adicionales tambi\u00e9n pueden mejorar el rendimiento de las consultas<\/li>\n<li>La consulta utiliza N1QL 6.5 ANSI JOIN Soporte para Expresi\u00f3n y Subconsulta T\u00e9rmino<\/li>\n<\/ol>\n<pre class=\"font:consolas font-size:10 lang:python decode:true\" title=\"Fragmento de c\u00f3digo Python para aplanar una jerarqu\u00eda\"># Python code to flatten a JSON document in Couchbase bucket\r\nfrom couchbase.cluster import Cluster\r\nfrom couchbase.cluster import PasswordAuthenticator\r\nfrom couchbase.exceptions import NotFoundError\r\nfrom couchbase.bucket import Bucket\r\nfrom couchbase.n1ql import N1QLQuery\r\n\r\ndef flatten_hierarchy(cb,bucketname,src_doc_type,num_hier_level,node_id_col, parent_id_col):\r\n# Example: flatten_hierarchy(cb,args.bucket,'user',4,'id','managerid')\r\n# cb - couchbase bucket handle\r\n# bucketname - name of the bucket for the source and target documents \r\n# src_doc_type - the type value of the source document\r\n# num_hier_level - specifies the number of levels that are needed. Should be the max depth of the hierarchy\r\n# node_id - the field name in the document for the key node id\r\n# parent_node_id - the parent field \r\n#\r\n    gen_doc_type = '_'+src_doc_type+'_hier'\r\n    if (num_hier_level &gt; 1):\r\n        qstr_ins = 'INSERT into '+bucketname+' (KEY UUID(), VALUE ndoc) '\r\n        qstr_sel = 'SELECT { \"type\":\"'+gen_doc_type+'\"'     \r\n        for i in range(1,num_hier_level+1):\r\n            qstr_sel += ',\"id'+str(i)+'\":l'+str(i)+'.'+node_id_col\r\n        qstr_sel += '} ndoc'     \r\n        qstr_sel_one =  ' SELECT '+node_id_col+','+parent_id_col+' FROM '+bucketname+' WHERE type=\"'+src_doc_type+'\"'\r\n        for i in range(1,num_hier_level+1):\r\n            if (i==1):\r\n                qstr_sel += ' FROM ('+qstr_sel_one+') l'+str(i)\r\n            else:\r\n                qstr_sel += ' LEFT OUTER JOIN ('+qstr_sel_one\r\n                qstr_sel += ') l'+str(i)+' ON l'+str(i-1)+'.'+parent_id_col+' = l'+str(i)+'.'+node_id_col\r\n        try:\r\n            #q = N1QLQuery(qstring)\r\n            rows = cb.n1ql_query(qstr_ins+qstr_sel).execute()\r\n        except Exception as e:\r\n                print(\"query error\",e)\r\n        # generate connect by\r\n\r\n    if (num_hier_level &gt; 1):\r\n        qstr_ins = 'INSERT into '+bucketname+' (KEY UUID(), VALUE ndoc) '\r\n        qstr_sel = 'SELECT { \"id\":ll.child,\"parent\":ll.parent,\"level\":ll.level ,\"type\":\"'+gen_doc_type+'_level\" } ndoc FROM ('\r\n        for i in range(1,num_hier_level):\r\n            if (i&gt;1):\r\n                qstr_sel += 'UNION ALL '\r\n            qstr_sel += 'SELECT id'+str(i+1)+' parent, id1 child,'+str(i)+' level FROM '+bucketname+' WHERE type=\"'+gen_doc_type+'\" and id'+str(i+1)+' IS NOT NULL '\r\n        qstr_sel += ') ll'\r\n        try:\r\n            rows = cb.n1ql_query(qstr_ins+qstr_sel).execute()\r\n        except Exception as e:\r\n            print(\"query error\",e)\r\n    return<\/pre>\n<h4><b>Recursos<\/b><\/h4>\n<ul>\n<li><i>Descargar<\/i>:\u00a0<a href=\"https:\/\/www.couchbase.com\/blog\/es\/downloads\/?family=server&amp;product=couchbase-server-developer\">Descargar Couchbase Server 6.5<\/a><i><\/i><\/li>\n<li><i>Documentaci\u00f3n<\/i>:\u00a0<a href=\"https:\/\/docs.couchbase.com\/server\/6.5\/introduction\/whats-new.html\">Novedades de Couchbase Server 6.5<\/a><i><\/i><\/li>\n<li><a href=\"https:\/\/www.couchbase.com\/blog\/es\/tag\/6-5\/\"><b>Todos los blogs de 6.5<\/b><\/a><\/li>\n<\/ul>\n<p>Nos encantar\u00eda que nos dijera qu\u00e9 le han parecido las funciones de la versi\u00f3n 6.5 y en qu\u00e9 beneficiar\u00e1n a su empresa en el futuro. Por favor, comparta su opini\u00f3n a trav\u00e9s de los comentarios o en el\u00a0<a href=\"https:\/\/www.couchbase.com\/blog\/es\/forums\/\">foro<\/a>.<\/p>","protected":false},"excerpt":{"rendered":"<p>A data construct that often appears in business application is the hierarchical data structure. Hierarchy captures the parent-child relationship often between the same object. For instance a company structure captures the reporting line between employees. Business organization captures the relationship [&hellip;]<\/p>\n","protected":false},"author":26326,"featured_media":6420,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"footnotes":""},"categories":[1814,1815,1819,1812],"tags":[2378],"ppma_author":[8919],"class_list":["post-6386","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-application-design","category-best-practices-and-tutorials","category-data-modeling","category-n1ql-query","tag-6-5"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v27.3 (Yoast SEO v27.3) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>N1QL query with Self Referencing Hierarchy - The Couchbase Blog<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.couchbase.com\/blog\/es\/n1ql-query-with-self-referencing-hierarchy\/\" \/>\n<meta property=\"og:locale\" content=\"es_MX\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"N1QL query with Self Referencing Hierarchy\" \/>\n<meta property=\"og:description\" content=\"A data construct that often appears in business application is the hierarchical data structure. Hierarchy captures the parent-child relationship often between the same object. For instance a company structure captures the reporting line between employees. Business organization captures the relationship [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.couchbase.com\/blog\/es\/n1ql-query-with-self-referencing-hierarchy\/\" \/>\n<meta property=\"og:site_name\" content=\"The Couchbase Blog\" \/>\n<meta property=\"article:published_time\" content=\"2019-02-18T03:35:55+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-06-14T00:22:10+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1774\" \/>\n\t<meta property=\"og:image:height\" content=\"778\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Binh Le\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Binh Le\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutos\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/n1ql-query-with-self-referencing-hierarchy\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/n1ql-query-with-self-referencing-hierarchy\\\/\"},\"author\":{\"name\":\"Binh Le\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/#\\\/schema\\\/person\\\/f89064928e262c71eb43bee996c48c63\"},\"headline\":\"N1QL query with Self Referencing Hierarchy\",\"datePublished\":\"2019-02-18T03:35:55+00:00\",\"dateModified\":\"2025-06-14T00:22:10+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/n1ql-query-with-self-referencing-hierarchy\\\/\"},\"wordCount\":717,\"commentCount\":5,\"publisher\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/n1ql-query-with-self-referencing-hierarchy\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/wp-content\\\/uploads\\\/sites\\\/1\\\/2019\\\/02\\\/Screen-Shot-2019-02-20-at-8.59.12-AM.png\",\"keywords\":[\"6.5\"],\"articleSection\":[\"Application Design\",\"Best Practices and Tutorials\",\"Data Modeling\",\"SQL++ \\\/ N1QL Query\"],\"inLanguage\":\"es\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/n1ql-query-with-self-referencing-hierarchy\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/n1ql-query-with-self-referencing-hierarchy\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/n1ql-query-with-self-referencing-hierarchy\\\/\",\"name\":\"N1QL query with Self Referencing Hierarchy - The Couchbase Blog\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/n1ql-query-with-self-referencing-hierarchy\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/n1ql-query-with-self-referencing-hierarchy\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/wp-content\\\/uploads\\\/sites\\\/1\\\/2019\\\/02\\\/Screen-Shot-2019-02-20-at-8.59.12-AM.png\",\"datePublished\":\"2019-02-18T03:35:55+00:00\",\"dateModified\":\"2025-06-14T00:22:10+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/n1ql-query-with-self-referencing-hierarchy\\\/#breadcrumb\"},\"inLanguage\":\"es\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/n1ql-query-with-self-referencing-hierarchy\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"es\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/n1ql-query-with-self-referencing-hierarchy\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/wp-content\\\/uploads\\\/sites\\\/1\\\/2019\\\/02\\\/Screen-Shot-2019-02-20-at-8.59.12-AM.png\",\"contentUrl\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/wp-content\\\/uploads\\\/sites\\\/1\\\/2019\\\/02\\\/Screen-Shot-2019-02-20-at-8.59.12-AM.png\",\"width\":1774,\"height\":778},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/n1ql-query-with-self-referencing-hierarchy\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"N1QL query with Self Referencing Hierarchy\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/\",\"name\":\"The Couchbase Blog\",\"description\":\"Couchbase, the NoSQL Database\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"es\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/#organization\",\"name\":\"The Couchbase Blog\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"es\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/wp-content\\\/uploads\\\/2023\\\/04\\\/admin-logo.png\",\"contentUrl\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/wp-content\\\/uploads\\\/2023\\\/04\\\/admin-logo.png\",\"width\":218,\"height\":34,\"caption\":\"The Couchbase Blog\"},\"image\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/#\\\/schema\\\/person\\\/f89064928e262c71eb43bee996c48c63\",\"name\":\"Binh Le\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"es\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/a939f48df6447844a8780bec264bb3be21d589336f3915fabc557075a68fa374?s=96&d=mm&r=g5b68c37e30928a9d7b2c8470b1a303b7\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/a939f48df6447844a8780bec264bb3be21d589336f3915fabc557075a68fa374?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/a939f48df6447844a8780bec264bb3be21d589336f3915fabc557075a68fa374?s=96&d=mm&r=g\",\"caption\":\"Binh Le\"},\"description\":\"Binh Le is a Principal Product Manager for Couchbase Query service. Prior to Couchbase, he worked at Oracle and led the product management team for Sales Cloud Analytics and CRM OnDemand. Binh holds a Bachelor's Degree in Computer Science from the University of Brighton, UK.\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/blog\\\/es\\\/author\\\/binh-le-2\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"N1QL query with Self Referencing Hierarchy - The Couchbase Blog","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.couchbase.com\/blog\/es\/n1ql-query-with-self-referencing-hierarchy\/","og_locale":"es_MX","og_type":"article","og_title":"N1QL query with Self Referencing Hierarchy","og_description":"A data construct that often appears in business application is the hierarchical data structure. Hierarchy captures the parent-child relationship often between the same object. For instance a company structure captures the reporting line between employees. Business organization captures the relationship [&hellip;]","og_url":"https:\/\/www.couchbase.com\/blog\/es\/n1ql-query-with-self-referencing-hierarchy\/","og_site_name":"The Couchbase Blog","article_published_time":"2019-02-18T03:35:55+00:00","article_modified_time":"2025-06-14T00:22:10+00:00","og_image":[{"width":1774,"height":778,"url":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM.png","type":"image\/png"}],"author":"Binh Le","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Binh Le","Est. reading time":"6 minutos"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.couchbase.com\/blog\/n1ql-query-with-self-referencing-hierarchy\/#article","isPartOf":{"@id":"https:\/\/www.couchbase.com\/blog\/n1ql-query-with-self-referencing-hierarchy\/"},"author":{"name":"Binh Le","@id":"https:\/\/www.couchbase.com\/blog\/#\/schema\/person\/f89064928e262c71eb43bee996c48c63"},"headline":"N1QL query with Self Referencing Hierarchy","datePublished":"2019-02-18T03:35:55+00:00","dateModified":"2025-06-14T00:22:10+00:00","mainEntityOfPage":{"@id":"https:\/\/www.couchbase.com\/blog\/n1ql-query-with-self-referencing-hierarchy\/"},"wordCount":717,"commentCount":5,"publisher":{"@id":"https:\/\/www.couchbase.com\/blog\/#organization"},"image":{"@id":"https:\/\/www.couchbase.com\/blog\/n1ql-query-with-self-referencing-hierarchy\/#primaryimage"},"thumbnailUrl":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM.png","keywords":["6.5"],"articleSection":["Application Design","Best Practices and Tutorials","Data Modeling","SQL++ \/ N1QL Query"],"inLanguage":"es","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.couchbase.com\/blog\/n1ql-query-with-self-referencing-hierarchy\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.couchbase.com\/blog\/n1ql-query-with-self-referencing-hierarchy\/","url":"https:\/\/www.couchbase.com\/blog\/n1ql-query-with-self-referencing-hierarchy\/","name":"N1QL query with Self Referencing Hierarchy - The Couchbase Blog","isPartOf":{"@id":"https:\/\/www.couchbase.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.couchbase.com\/blog\/n1ql-query-with-self-referencing-hierarchy\/#primaryimage"},"image":{"@id":"https:\/\/www.couchbase.com\/blog\/n1ql-query-with-self-referencing-hierarchy\/#primaryimage"},"thumbnailUrl":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM.png","datePublished":"2019-02-18T03:35:55+00:00","dateModified":"2025-06-14T00:22:10+00:00","breadcrumb":{"@id":"https:\/\/www.couchbase.com\/blog\/n1ql-query-with-self-referencing-hierarchy\/#breadcrumb"},"inLanguage":"es","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.couchbase.com\/blog\/n1ql-query-with-self-referencing-hierarchy\/"]}]},{"@type":"ImageObject","inLanguage":"es","@id":"https:\/\/www.couchbase.com\/blog\/n1ql-query-with-self-referencing-hierarchy\/#primaryimage","url":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM.png","contentUrl":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2019\/02\/Screen-Shot-2019-02-20-at-8.59.12-AM.png","width":1774,"height":778},{"@type":"BreadcrumbList","@id":"https:\/\/www.couchbase.com\/blog\/n1ql-query-with-self-referencing-hierarchy\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.couchbase.com\/blog\/"},{"@type":"ListItem","position":2,"name":"N1QL query with Self Referencing Hierarchy"}]},{"@type":"WebSite","@id":"https:\/\/www.couchbase.com\/blog\/#website","url":"https:\/\/www.couchbase.com\/blog\/","name":"El blog de Couchbase","description":"Couchbase, la base de datos NoSQL","publisher":{"@id":"https:\/\/www.couchbase.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.couchbase.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"es"},{"@type":"Organization","@id":"https:\/\/www.couchbase.com\/blog\/#organization","name":"El blog de Couchbase","url":"https:\/\/www.couchbase.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"es","@id":"https:\/\/www.couchbase.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/2023\/04\/admin-logo.png","contentUrl":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/2023\/04\/admin-logo.png","width":218,"height":34,"caption":"The Couchbase Blog"},"image":{"@id":"https:\/\/www.couchbase.com\/blog\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/www.couchbase.com\/blog\/#\/schema\/person\/f89064928e262c71eb43bee996c48c63","name":"Binh Le","image":{"@type":"ImageObject","inLanguage":"es","@id":"https:\/\/secure.gravatar.com\/avatar\/a939f48df6447844a8780bec264bb3be21d589336f3915fabc557075a68fa374?s=96&d=mm&r=g5b68c37e30928a9d7b2c8470b1a303b7","url":"https:\/\/secure.gravatar.com\/avatar\/a939f48df6447844a8780bec264bb3be21d589336f3915fabc557075a68fa374?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/a939f48df6447844a8780bec264bb3be21d589336f3915fabc557075a68fa374?s=96&d=mm&r=g","caption":"Binh Le"},"description":"Binh Le is a Principal Product Manager for Couchbase Query service. Prior to Couchbase, he worked at Oracle and led the product management team for Sales Cloud Analytics and CRM OnDemand. Binh holds a Bachelor's Degree in Computer Science from the University of Brighton, UK.","url":"https:\/\/www.couchbase.com\/blog\/es\/author\/binh-le-2\/"}]}},"acf":[],"authors":[{"term_id":8919,"user_id":26326,"is_guest":0,"slug":"binh-le-2","display_name":"Binh Le","avatar_url":"https:\/\/secure.gravatar.com\/avatar\/a939f48df6447844a8780bec264bb3be21d589336f3915fabc557075a68fa374?s=96&d=mm&r=g","0":null,"1":"","2":"","3":"","4":"","5":"","6":"","7":"","8":""}],"_links":{"self":[{"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/posts\/6386","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/users\/26326"}],"replies":[{"embeddable":true,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/comments?post=6386"}],"version-history":[{"count":0,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/posts\/6386\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/media\/6420"}],"wp:attachment":[{"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/media?parent=6386"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/categories?post=6386"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/tags?post=6386"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/ppma_author?post=6386"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}