Search code examples
azureazure-stream-analytics

Limit 1 or Top 1 in Azure Stream Analytics Query


I have written below Stream Analytics Query to get Device Offline status alert. Query gives me an alert if no input received from device in the last 5 minute.

I need last telematic record (Last known location) of that device, but I'm getting all data sent for that device. I tried LAST and TopOne but all are windowing method. Is there any other solution than a custom function?

SELECT
     t1.header.serialNumber as serialNumber,t1.header.make as 
     make,t1.header.messageTimestamp as MessageTime,'Device Offline Alert' as 
     alertType
INTO
[alertOutput2]
FROM
  [tsfInput] t1 TIMESTAMP BY header.messageTimestamp
LEFT OUTER JOIN [tsfInput] t2 TIMESTAMP BY header.messageTimestamp
ON
     t1.header.serialNumber=t2.header.serialNumber AND 
     t1.header.make=t2.header.make
     AND DATEDIFF(minute, t1, t2) BETWEEN 1 and 5
     WHERE t2.serialNumber IS NULL

Sample Input

{
"header": {
    "assetKey": 8910053376183227000,
    "make": "CAT36",
    "serialNumber": "Truck36",
    "deviceType": "A5:N2",
    "isPriority": false,
    "isReplay": true
}
}

Solution

  • I'm able to fix query but not 100 percent. After removing below line from query and it's working, still not clear why it is not working with TimeStamp

    TIMESTAMP BY header.messageTimestamp

    I have 2 queries 1 Device Online Alert and 2nd for Device Offline alert

    SELECT
    *,'Device Online Alert' as alertType
    INTO
        [alertOutput]
    FROM
    [tsfInput] 
    WHERE ISFIRST(mi, 5) OVER (PARTITION BY header.serialNumber,header.make) = 1
    
    SELECT t1.*,'Device Offline Alert' as alertType 
    INTO 
     [alertOutput2] 
    FROM [tsfInput] t1 
     LEFT OUTER JOIN [tsfInput] t2 
    ON t1.header.serialNumber=t2.header.serialNumber AND t1.header.make=t2.header.make 
    AND DATEDIFF(minute, t1, t2) BETWEEN 1 and 5 
    WHERE t2.header IS NULL