在ServiceNow开箱实例中查询cmdb_rel_ci表特定关联类型的父类计数
cmdb_rel_ci Hey there! Let's work through this ServiceNow aggregation task you're tackling in your out-of-the-box instance. You're looking to pull unique parent.sys_class_name values and their counts from the cmdb_rel_ci table, filtered to only the "In Rack::Rack contains" relationship type (sys_id: e76b8c7b0a0a0aa70082c9f7c2f9dc64).
Your initial script has the right foundation, but we need to add a couple critical pieces to get the grouped counts you want. Here's the full, working version:
// Initialize GlideAggregate on the cmdb_rel_ci table var count = new GlideAggregate('cmdb_rel_ci'); // Filter for the specific "In Rack::Rack contains" relationship type count.addQuery('type','e76b8c7b0a0a0aa70082c9f7c2f9dc64'); // Define the aggregate: count occurrences of each unique parent.sys_class_name count.addAggregate('COUNT', 'parent.sys_class_name'); // **Critical step**: Group results by the class name to get unique values count.groupBy('parent.sys_class_name'); // Run the query count.query(); // Loop through results to access each class name and its count while (count.next()) { // Get the friendly display name of the class (e.g., "Server" instead of "cmdb_ci_server") var className = count.parent.sys_class_name.getDisplayValue(); // Get the raw sys_class_name value if you need it for further queries var rawClassName = count.parent.sys_class_name.toString(); // Extract the count for this class var classCount = count.getAggregate('COUNT', 'parent.sys_class_name'); // Log the result (adjust this based on where you're running the script) gs.info(`Class: ${className} (${rawClassName}) | Count: ${classCount}`); // If you need to store results for later use (e.g., in a REST response), use an array: // results.push({className: className, rawClass: rawClassName, count: classCount}); }
Key Notes to Make This Work:
groupBy()is mandatory: Without this line, GlideAggregate will just return a single total count of all matching records, not split by each unique class name.- Display vs. Raw Value: Use
getDisplayValue()for user-friendly class names, ortoString()if you need the actual sys_class_name string (likecmdb_ci_server) for other operations. - Script Context: This works in background scripts, UI actions, scripted REST APIs, etc. Adjust how you output/use the results based on where you're running it.
If you want to package the results into a structured object (for example, to return in a REST endpoint), you can initialize an array before the loop and push each result into it, like the commented line in the script.
内容的提问来源于stack exchange,提问作者Done With Fun

