깊이 중첩된 객체를 정확히 일치 검색 - PostgreSQL

목차
* 🚀 INTRO
* 🎯 GOAL
* 🏁 SOLUTION
* 🙏 THANK YOU

🚀 소개

Hi all! In this post I'll try to showcase the problem I faced recently. It is regarding the PostgreSQL database and how to query for an exact text match in the deeply nested objects and array of objects.

🎯 목표

Let's consider that you are making a platform that allows people to register, create profile, add skills they poses and land a job offer. Let's assume that we are currently interested in creating a search engine that will search only for the exact match of the skill (e.g. "cooking") and It should return only the data that matched the search term.

Also, let's assume that we are storing the table that has a column called "sections" and it is of "jsonb" type. That object contains objects for "skills" (which contains an array of objects called "items"), "languages", "hobbies" etc.

Read more about JSON column in PostgreSQL docs

JSON 객체 예시



sections: {
   skills: {
      items: [{
         name: 'cooking'
      }]
   },
   languages: {...}
   hobbies: {...}
}

따라서 우리의 현재 목표는 "고용주"사용자가 입력한 검색어(이 경우에는 '요리')를 얻고 이 용어와 정확히 일치하는 모든 사용자 프로필을 찾는 것입니다.

🏁 솔루션

We can achieve this in the following manner:

SELECT *
FROM user_profile up
WHERE up.sections->'skills' @> '{"items":[{ "name": "cooking"}]}';

This will return all the user profiles from the user_profile table, that matched the skill search term exactly.

🙏 읽어주셔서 감사합니다!

Please leave a comment, tell me about you, about your work, comment your thoughts, connect with me!

☕ SUPPORT ME AND KEEP ME FOCUSED!



즐거운 해킹 시간 되세요! 😊

좋은 웹페이지 즐겨찾기