Saturday, February 21, 2015

Like-Search for MNESIA using ERLANG

I searched every where in the Internet for a way to implement 'like-search' function using ERLANG for MNESIA (Similar to what we experience in MySQL). Unfortunately I couldn't find it. Finally my one of friend (Sisila Priyankara@Sri Lanka) wrote a function exactly which I expected.
I would like to share his function as a module with you. You can hack this module and develop as you want.

  • qlc_tbl.hrl is the place where you should mention the record definitions of the tables which are going to be used with this module.
eg :- (record definition for a table called service) 
 -record(service, {  id :: integer(),
                    name :: string(),
                    description :: string(),
                    access_code :: string(),
                    type :: atom(),
                    codec :: string(),
                    access_type :: atom(),
                    status :: atom(),
                    created_date :: tuple(),
                    created_by :: integer(),
                    port_number :: integer(),
                    svn_revision :: integer(),
                    deploy_count :: integer(),
                    company_id :: integer(),
                    department_id :: integer(),
                    dtmf_payload :: integer()
                 }).
-type service() :: #service{}. 


 
-module(like_search).

-export([search/3]).
-include_lib("stdlib/include/qlc.hrl").
-include("../conf/qlc_tbl.hrl").

-spec search(Table :: atom(), TupleElementIndex :: integer(), Word :: float() | atom() | integer() | list()) -> RecordList :: list().
%% @doc like search for a single field in a single table. Search will be done from begining
search(Table, TupleElementIndex, Word)->
    Fun = fun() ->
    qlc:eval(
    qlc:q(
    [X || X <- mnesia:table(Table), string:str(toString(element(TupleElementIndex, X)), toString(Word)) ==1]
    ))
    end,
    {atomic, RecordList} = mnesia:transaction(Fun),
    RecordList.

-spec toString(Value :: float() | atom() | integer() | list()) -> string().
toString(Value) ->
        if
        is_float(Value) ->
%                float_to_list(io_lib:format("~.2f",[Value]));
%        float_to_list(Value);
        lists:nth(1,io_lib:format("~.2f", [Value]));
        is_atom(Value) ->
                atom_to_list(Value);
        is_integer(Value) ->
                integer_to_list(Value);
        is_list(Value) ->
                Value;
        true ->
                "--"
        end.

Labels: , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home