How to search for messages with mentions

Search for messages

In previous article, I've explained how to use the Microsoft Search API to search for messages.

The Microsoft Search API can be accessed through the /search/query endpoint. You simply send POST request with the body where you specify the type of the resource to be searched and query terms.

POST https://graph.microsoft.com/v1.0/search/query
{
    "requests": [
        {
            "entityTypes": [
                "message"
            ],
            "query": {
                "queryString": "vacation"
            }
        }
    ]
}

The search term and any filters are specified in queryString.

Search for messages with @mentions

In previous article I've described how you can work with @mentions and what is supported with the Graph API.

To find all messages where the signed-in user was/wasn't mentioned, use the keyword isMentioned in the query string. Allowed values are either true or false.

POST https://graph.microsoft.com/v1.0/search/query
{
    "requests": [
        {
            "entityTypes": [
                "message"
            ],
            "query": {
                "queryString": "isMentioned:true AND received:\"this year\""
            }
        }
    ]
}

Despite the fact that the Graph API supports @mentions only in beta, the searching works fine with v1.0.

If you are using .NET SDK for the Graph API:

var graphClient = new GraphServiceClient(credential);

var requestBody = new QueryPostRequestBody
{
    Requests = new List<SearchRequest>
    {
        new SearchRequest
        {
            EntityTypes = new List<EntityType?>
            {
                EntityType.Message
            },
            Query = new SearchQuery
            {
                QueryString = "isMentioned:true AND received:\"this year\""
            }
        }
    }
};

var result = await graphClient.Search.Query.PostAsQueryPostResponseAsync(requestBody);

var hits = result.Value[0].HitsContainers[0].Hits;

foreach (var searchHit in hits)
{
    Console.WriteLine($"Message id: {searchHit.HitId}");
    if (searchHit.Resource is Message message)
    {
        Console.WriteLine($"Subject: {message.Subject}");
        Console.WriteLine($"Body preview: {message.BodyPreview}");
    }
}
0
Buy Me a Coffee at ko-fi.com
An error has occurred. This application may no longer respond until reloaded. Reload x