February 10th, 2022

Microsoft Graph Mailbag – Search DriveItems for Only Files

In today’s Microsoft Graph Mailbag post, we’ll use the Microsoft Search APIs on Microsoft Graph to return only files/documents.

Microsoft Graph logo with search magnifying glass and document icons

Please be sure to follow this blog series using https://aka.ms/MSGraphMailbag or with RSS using https://devblogs.microsoft.com/microsoft365dev/tag/MSGraphMailbag.

Introduction

Recently, I was reviewing questions on Microsoft Q&A. I found an interesting question on How to differentiate between folders and files. The author asked how to use the Microsoft Search APIs on Microsoft Graph to search for only files/documents from OneDrive or SharePoint. By default, when you specify entityType of “driveItem,” this will return files, folders, pages, and news. The following is a sample query from Microsoft Graph Explorer to search for “driveItem” content.

POST https://graph.microsoft.com/v1.0/search/query

{
  "requests":[
    {
      "entityTypes":[
        "driveItem"
      ],
      "query":{
        "queryString":"contoso"
      }
    }
  ]
}

I ran the above request in one my lab tenants. The following screenshot shows the sample output. Notice the first result is a site page.

Screenshot of Search API on Microsoft Graph Explorer for driveItems

Solution

In order to filter for only files/documents, you can add either of the following (ContentType or ContentTypeId) to the “queryString” property within the “query” element of your request.

"query": {
  "queryString": "test document AND ContentType:Document"
}

or

"query": {
  "queryString": "test document AND ContentTypeId:0x0101*"
}

I updated my sample query and re-ran in my lab tenant. Notice that the sample response now has fewer search hits, and the first result is now a file.

Screenshot of Search API sample request on Graph Explorer filtering for only files

Here is one of the final sample queries for filtering for only files/documents.

POST https://graph.microsoft.com/v1.0/search/query

{
  "requests":[
    {
      "entityTypes":[
        "driveItem"
      ],
      "query":{
        "queryString":"contoso AND ContentType:Document"
      }
    }
  ]
}

Conclusion

In this post we looked at the sample request to search for driveItems using the Microsoft Search APIs on Microsoft Graph. We then modified it to filter for only files/documents. You can use similar modifications to filter for other types of content as needed. Hopefully this will save you time and give you inspiration on how you can adapt the standard sample requests to retrieve the data you need with Microsoft Graph.

Today’s post was written by Brian T. Jackett, Principal PM with the Microsoft Graph Customer and Partner Experience (CPx) team. You can follow Brian on Twitter @BrianTJackett

0 comments

Discussion are closed.