Skip to content

Instantly share code, notes, and snippets.

@cloud8421
Created September 11, 2014 08:32
Show Gist options
  • Save cloud8421/e59a53be3b1f2a70a2b4 to your computer and use it in GitHub Desktop.
Save cloud8421/e59a53be3b1f2a70a2b4 to your computer and use it in GitHub Desktop.
qlc to filter by hour
-module(freyr_reading_queries).
-export([all/0, by_hour/1, by_device/1]).
-include_lib("stdlib/include/qlc.hrl").
-include("freyr_reading.hrl").
all() ->
#freyr_reading{_='_'}.
by_hour(Hour) ->
Query = qlc:q([Reading || Reading <- mnesia:table(freyr_reading),
{{'_','_','_'}, {Hour,'_','_'}} == Reading#freyr_reading.timestamp]),
qlc:eval(qlc:sort(Query, {order, fun timestamp_descending/2})).
%% #freyr_reading{timestamp={{'_','_','_'}, {Hour,'_','_'}}, _='_'}.
by_device(DeviceId) ->
Query = qlc:q([Reading || Reading <- mnesia:table(freyr_reading),
Reading#freyr_reading.device_id == DeviceId]),
qlc:eval(qlc:sort(Query, {order, fun timestamp_ascending/2})).
timestamp_ascending(A, B) ->
A#freyr_reading.timestamp < B#freyr_reading.timestamp.
timestamp_descending(A, B) ->
A#freyr_reading.timestamp > B#freyr_reading.timestamp.

I'm storing this data in a mnesia table:

-record(freyr_reading, {
          uuid,
          device_id,
          temperature,
          brightness,
          moisture,
          timestamp %% {{Year,Month,Day},{Hour,Minute,Second}}
         }).

I wanna query the table to return only the records which match a certain Hour, which I've done with a match.

#freyr_reading{timestamp={{'_','_','_'}, {Hour,'_','_'}}, _='_'}.

I'm trying now to do the same thing with qlc, but I can't get it to work.

I've tried:

qlc:q([Reading || Reading <- mnesia:table(freyr_reading),
                  {{'_','_','_'}, {Hour,'_','_'}} == Reading#freyr_reading.timestamp]).

But when executed, it returns an empty result.

@sinasamavati
Copy link

I think you should do the querying like this:

by_hour(Hour) ->
  Query = qlc:q([Reading || Reading <- mnesia:table(freyr_reading),
                            hours_match(Hour, Reading#freyr_reading.timestamp)]),
  qlc:eval(qlc:sort(Query, {order, fun timestamp_descending/2})).

hours_match(H, {_, {H, _, _}}) -> true;
hours_match(_, _) -> false.

@cloud8421
Copy link
Author

That works perfectly, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment