Skip to main content

Query for Relationships in BQL

This article describes how to query your data using the relationships between two data models and how to execute a query with multiple relationships.

You can use BQL to query for relationships between two data models or among multiple data models. For more information on relationships between data models see the data models article.

The following examples demonstrate how you can use relationships in your BQL queries.

Example I

In the first example, consider three data models: A, B, and C, where A is related to B and A is related to C, but B is not related to C. You can use BQL to return A that is related to both B and C.

In the following query, A is the Host data model, B is the ServicenowHost data model, and C is the QualysVMHost data model. There are hosts running ServiceNow and there are hosts running Qualys Vulnerability Management. (The relationship is SOURCED_FROM.) The query attempts to find hosts that are running both ServiceNow and Qualys Vulnerability Management:

FIND Host as h that SOURCED_FROM ServicenowHost as s 
and h that SOURCED_FROM QualysVmHost as q
return h.name, s.name, q.name limit 10

Example II

Following the same scenario in example I, you can also query for A that is related to B but not related to C.

The following query returns hosts that are running Qualys Vulnerability Management but not ServiceNow:

FIND Host as h that SOURCED_FROM QualysVmHost as q  
and h that NOT SOURCED_FROM ServicenowHost
return h.name, q.name

While the first query focuses on the need for both relationships to exist, the second query searches for and retrieves hosts that have the first, but not the second relationship.

Example III

The last example again uses three data models, A, B, and C, where A is related to B, and B is related to C, but A is not related to C. In the following query, A is the Person data model, B is the Host data model, and C is the Finding data model. The Person data model does not have a relationship with the Finding data model.

The following query illustrates how you can establish a connection between A and C by tethering the relationships from A to B and then from B to C. Specifically, the query returns a person’s last name and the number of findings that are related to this person:

Find Person as p that OWNS Host as h 
AND h THAT HAS Finding as f
return p.lastName, count(distinct f) as findings