Search code examples
kdb

Searching multiple strings using like


How to use like for searching mulitiple strings ?

q)\l sp.q

q)select from p where city like "lon*"
p | name  color weight city
--| -------------------------
p1| nut   red   12     london
p4| screw red   14     london
p6| cog   red   19     london

I want to search the city either starting with "lon" or "par", /: gives type error.

q)select from p where city like/: ("lon*";"par*")
'type

Solution

  • You need to use any when searching for multiple strings.

    q)select from p where any city like/: ("lon*";"par*")
    
    p | name  color weight city
    --| -------------------------
    p1| nut   red   12     london
    p2| bolt  green 17     paris
    p4| screw red   14     london
    p5| cam   blue  12     paris
    p6| cog   red   19     london
    

    When you search using the /: (each right ), it returns 2 vectors , one against the "lon*" search and another for "par*".

    (0!p)[`city] like/: ("lon*";"par*")
    (100101b;010010b)
    

    using any does the ORing and returns a single vector.

    any (0!p)[`city] like/: ("lon*";"par*")
    110111b
    

    Now getting the final result :

    (0!p) where any (0!p)[`city] like/: ("lon*";"par*")
    p  name  color weight city
    ----------------------------
    p1 nut   red   12     london
    p2 bolt  green 17     paris
    p4 screw red   14     london
    p5 cam   blue  12     paris
    p6 cog   red   19     london