1

I have this data in one column in postgresql

{
    "geometry":{
        "status":"Point",
        "coordinates":[
            -122.421583,
            37.795027    
        ]          
    },

and i using his query

select * from students where data_json LIKE '%status%' ;

Above query return results but this one does not

select * from students where data_json LIKE '%status:%' ;

How can fix that

1 Answer 1

3

Of course the 2nd one doesn't find a match, there's no status: text in the value. I think you wanted:

select * from students where data_json LIKE '%"status":%' 

... however, like most cases where you attempt text pattern matching on structured data this is in general a terrible idea that will bite you. Just a couple of problem examples:

{
    "somekey": "the value is \"status\": true"
}

... where "status": appears as part of the text value and will match even though it shouldn't, and:

{
    status : "blah"
}

where status has no quotes and a space between the quotes and colon. As far as JavaScript is concerned this is the same as "status": but it won't match.

If you're trying to find fields within json or extract fields from json, do it with a json parser. PL/V8 may be of interest, or the json libraries available for tools like pl/perl, pl/pythonu, etc. Future PostgreSQL versions will have functions to get a json key by path, test if a json value exists, etc, but 9.2 does not.

At this point you might be thinking "why don't I use regular expressions". Don't go there, you do not want to try to write a full JSON parser in regex. this blog entry is somewhat relevant.

Sign up to request clarification or add additional context in comments.

2 Comments

Can i use hstore for that type of search
@user194932147 hstore is flat, it doesn't have nested keys. You could probably write code to flatten json into a hstore and ignore/overwrite duplicate keys but it'd (a) be a bit unsafe and (b) require you to do most of the work you'd have to do for a proper json key search anyway. As I said, use PL/V8, PL/Perl, or similar to write a key lookup function or find one somebody else has already written. You can create functional indexes on the key lookup function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.