유용한 코드를 자유롭게 가져 오십시오. 또는 더 나은 아직, 당신은 관리자가되는 것을 환영합니다! 이 프로젝트를 보내 게 한 나의 가장 진심으로 사과드립니다. 나는 그것이 당신에게 불편을 겪지 않기를 바랍니다.
postgres node.js의 full-text 검색을 ORM으로 사용하여 속편을 사용합니다.
코드 예제를 확인하십시오.
이 라이브러리는 Postgres 전체 텍스트 검색 및 구체화 된보기를 사용하여 빠르고 강력하며 간단한 검색 쿼리를 실행합니다. 먼저 검색을 가능하게하려는 필드의 모든 값을 연결하여 ts_vector 로 변환하여 구체화 된보기를 만듭니다. 그런 다음 속편 모델에 searchByText 및 search 클래스 메소드를 추가하여 쿼리 문자열 또는 쿼리 문자열 및 옵션 JSON 개체에서 검색을 실행할 수 있습니다. 또한 모델에 대한 업데이트가 만들어 지거나 원할 때마다 구체화 된보기를 새로 고치기 위해 refresh 클래스 방법을 추가합니다.
예를 들어, 필름 데이터베이스 테이블이 있다고 가정 해 봅시다.
| ID | 이름 | 설명 | 도시 | release_date | 평가 |
|---|---|---|---|---|---|
| 1 | 도망자 | 다른 사람이 감옥에서 탈출합니다 | 시카고 | 1993-08-06 | 8 |
| 2 | 아름다운 마음 | 수학자에 관한 영화 | 뉴욕 | 2001-12-05 | 8 |
| 3 | 시카고 | 좋은 ol 'American Musical | 토론토 | 2002-12-10 | 7 |
| 4 | 흠없는 마음의 영원한 햇빛 | Jim Carrey가 코미디언이 아니었을 때 | 뉴욕 | 2004-03-19 | 8 |
우리는 이름, 설명 및 도시로 검색하고 평가 및 release_date에 의해 필터링을 허용하고자합니다. 또한 이름 필드에 설명과 도시보다 더 높은 무게를 제공하여 관련성에 따라 결과를 정렬하고 싶습니다. 따라서 검색을 실행하면 :
Film . searchByText ( "Chicago" ) ; // Returns [ Chicago, The Fugitive ]제목에 "시카고"라는 단어가있는 결과는 설명이나 도시에서 같은 단어를 가진 사람들 앞에 나타납니다. 따라서 영화 시카고는 먼저 나타나고 도망자는 두 번째가 될 것입니다.
검색 쿼리를 작성하여 관련성으로 주문하는 대신 특정 필드별로 필터링 및 주문을 추가 할 수도 있습니다.
Film . searchByText ( "Mind order:releaseDate" ) ; // Returns [ A Beautiful Mind, Eternal Sunshine of the Spotless Mind ]
// or
Film . searchByText ( "Mind releaseDate:<2002-01-01" ) ; // Returns [ A Beautiful Mind ]또한 하나의 모델의 필드에만 국한되지 않습니다. 관련 모델의 필드도 포함 할 수도 있습니다. 예를 들어, 데이터베이스에 외국 키로 필름과 관련된 Actor라는 데이터베이스에 다른 모델이 있다면 Actor 모델의 필드를 포함하여 필름 구체화 된보기에 포함시킬 수 있습니다. 이를 통해 다음과 같은 검색을 실행할 수 있습니다.
Film . searchByText ( "Tom Hanks" ) ; // Returns Tom Hanks movies이 도서관으로 더 많은 일을 할 수 있습니다. 설치 및 사용 방법에 대한 자세한 내용은 설치 및 사용 섹션을 확인하십시오. 설명서는 문서 섹션을 확인하십시오.
NPM pg-search-sequelize 패키지를 설치하십시오
npm i --save pg-search-sequelize그런 다음 구체화 된보기 모델 정의 파일에 필요하고 속편 모델을 전달하여 검색 할 수 있도록합니다.
let MyModel = sequelize . define ( ... ) ; // your sequelize model definition
let SearchModel = require ( 'pg-search-sequelize' ) ; // Require the pg-search-sequelize library
MyModel = new SearchModel ( MyModel ) ; // Construct a SearchModel out of the model you defined above. This adds `search`, `searchByText`, and `refresh` class methods to your model.모델을 정의하는 방법과 구체화 된보기를 만드는 방법은 사용법을 참조하십시오.
이제이 라이브러리가 무엇을 가능하게하는지 엿볼 수있게되었으므로 설정 단계에 도달합시다.
속편 마이그레이션 도구를 사용하는 경우 QueryInterface 클래스에서 제공하는 createMaterializedView(name, referenceModel, attributes, options) 도우미 기능을 사용할 수 있습니다.
const QueryInterface = require ( "pg-search-sequelize" ) . QueryInterface ;
const models = require ( "../models" ) ;
// The model we're creating the materialized view for
const referenceModel = models . Film ;
const materializedViewName = "film_materialized_view" ;
const attributes = { // field: weight. Every field has a weight to calculate how relevant the search results are.
name : "A" , // name has the highest weight.
description : "B" ,
city : "C" // city has a lower weight than title and description
}
const options = {
include : [ // You can also include fields from associated models
{
model : models . Actor ,
foreignKey : "actor_id" ,
targetKey : "id" ,
associationType : "hasMany" , // association types are: belongsTo, hasOne, or hasMany
attributes : { // Those attributes get added to the materialized view's search document and will also be searched just like the other fields
first_name : "D" ,
last_name : "D" ,
date_of_birth : "D"
}
}
]
}
module . exports : {
up : queryInterface => new QueryInterface ( queryInterface ) . createMaterializedView ( materializedViewName , referenceModel , attributes , options ) ,
down : queryInterface => new QueryInterface ( queryInterface ) . dropMaterializedView ( materializedViewName )
}속편 마이그레이션 도구를 사용하지 않으면 선호하는 방식으로 구체화 된보기를 자유롭게 작성하십시오.
구체화 된보기의 모델을 다른 속편 모델을 정의하는 것과 같은 방식으로 정의하십시오. 유일한 차이점은 모델 정의 옵션에 referenceModel 속성을 추가해야한다는 것입니다. 그런 다음 방금 정의한 구체화 된보기 모델에서 SearchModel 구성하십시오.
let SearchModel = require ( "pg-search-sequelize" ) ;
let FilmMaterializedView = sequelize . define ( 'FilmMaterializedView' , {
name : DataTypes . STRING ,
rating : DataTypes . INTEGER ,
document : DataTypes . TEXT
} , {
referenceModel : models . Film // The model for which we're defining the materialized view
} ) ;
FilmMaterializedView = new SearchModel ( FilmMaterializedView ) ; // Adds search, searchByText, and refresh class methods to the model. 이제 materializedViewModel.search(query, options) 또는 materializedViewModel.searchByText(query) 를 호출하여 모델 및 해당 협회에서 전체 텍스트 검색을 실행할 수 있습니다.
models . Film . searchByText ( "Mind" ) ; // Returns [ A Beautiful Mind, Eternal Sunshine of the Spotless Mind ]
// The following command searches for instances that match the search query,
// filters by those with releaseDate later than 2002, and orders the results by name field
models . Film . searchByText ( "Mind releaseDate:>2002 order:name" ) ; // Returns [ Eternal Sunshine of the Spotless Mind ]
// Or if you don't like strings, you can pass those properties in a JSON object
// The following returns the same as the code above; i.e. [ Eternal Sunshine of the Spotless Mind ]
models . Film . search ( "Mind" , {
where : {
releaseDate : { operator : ">" , value : "2002-01-01" }
} ,
order : [ [ "name" , "ASC" ] ]
}모델에 대한 최신 변경 사항으로 구체화 된보기를 새로 고치는 것을 잊지 마십시오. 이를 수행하는 한 가지 방법은 모델에서 AfterCreate, After Update 및 Afterdelete Hook를 만들어 구체화 된보기를 새로 고치는 것입니다.
sequelize . define ( 'Film' , attributes , {
hooks : {
afterCreate : ( ) => FilmMaterializedView . refresh ( ) ,
afterUpdate : ( ) => FilmMaterializedView . refresh ( ) ,
afterDelete : ( ) => FilmMaterializedView . refresh ( )
}
} ) ;또는 x 시간마다 구체화 된보기를 새로 고치는 작업 스케줄러를 가질 수 있습니다.
문서 섹션으로 가서 어떤 검색을 할 수 있는지 알아보십시오.
PG Search -Sequelize에는 2 개의 클래스, SearchModel 및 QueryInterface 가 있습니다.
SearchModel 클래스는 구체화 된 View Sequelize 모델에 검색 및 새로 고침 클래스 메소드를 추가하는 데 사용하는 것입니다. SearchModel 클래스에 액세스하려면 require("pg-search-sequelize") . SearchModel 클래스 MyModel = new SearchModel(MyModel) 으로 구성하는 모델에서 다음 기능을 호출 할 수 있습니다.
검색 쿼리 문자열과 옵션 객체를 사용하여 검색 구체화 된보기 모델.
query - 검색 쿼리 문자열.optionswhere - 결과를 제한하는 필터. /*
Format:
options.where = {
attribute: {
operator: ">, <, =, >=, <=, @@, ilike, etc.",
value: "some value"
}
*/
// Example:
options . where = {
releaseDate : {
operator : ">" ,
value : "2012-01-01"
}
}attributes - 반환 할 속성의 배열. 전. options . attributes = [ "name" , "releaseDate" , "rating" ]order - 첫 번째 값이 속성 이름이고 두 번째 값은 방향입니다. 예를 들어: options . order = [
[ "name" , "ASC" ] ,
[ "releaseDate" , "DESC" ] ,
[ "rating" , "DESC" ]
] Promise - 옵션 개체에 지정된 속성, 구체화 된보기 모델의 defaultScope 또는 구체화 된보기 모델 정의의 모든 속성이있는 검색 결과 인스턴스 배열.
텍스트 쿼리만으로 구체화 된보기 모델을 검색합니다. 검색 API 엔드 포인트를 모델에 노출시키는 데 특히 유용하므로 검색 쿼리 문자열을 구문 분석 할 염려가 없습니다.
query - 주문할 쿼리 텍스트, 필터 및 필드의 문자열. // --------------
// Simple search
// --------------
Film . searchByText ( "Beautiful" ) ; // WHERE to_tsquery('Beautiful') @@ document
// --------------
// Ordering
// --------------
// Search and order the results by rating in ascending order
Film . search ( "Beautiful order:rating" ) ; // WHERE to_tsquery('Beatiful') @@ document ORDER BY ts_rank(document, to_tsquery('Beautiful')), rating ASC
// Or to invert the order to descending order, prepend the field name by an exclamation point
Film . searchByText ( "Beautiful order:!rating" ) ; // WHERE to_tsquery('Beatiful') @@ document ORDER BY ts_rank(document, to_tsquery('Beautiful')), rating DESC
// --------------
// Filtering
// --------------
// Searches for a movie that has the text "Beautiful" in any of its fields and "brilliant mathematician" in the description.
Film . searchByText ( "Beatiful description:brilliant mathematician" ) ; // WHERE to_tsquery('Beatiful') @@ document AND description ILIKE %brilliant mathematician%
// You can also use comparison operators: =, >, <. >=, <=
Film . searchByText ( "Beautiful rating:>=7" ) // WHERE to_tsquery('Beautiful') @@ document AND rating >= 7
// If no operator is passed to the filter, an ILIKE operator is used. Just as seen in the first filtering example.
// If the field's type doesn't work with ILIKE, it is cast to TEXT.
Film . searchByText ( "Beautiful releaseDate:200" ) // WHERE to_tsquery('Beautiful') @@ document AND release_date::TEXT ILIKE 200 Promise - 구체화 된보기 모델의 defaultScope 검색 속성 또는 구체화 된보기 모델 정의의 모든 속성이있는 검색 결과 인스턴스 배열.
구체화 된보기를 새로 고칩니다. 전. models.Film.afterCreate(() => MaterializedViews.Film.refresh())
QueryInterface 클래스는 마이그레이션을 실행하기위한 것입니다. 즉, 구체화 된보기를 생성하고 떨어 뜨립니다. QueryInterface 클래스 down 액세스 queryInterface ( "PG up require("pg-search-sequelize").QueryInterface
let QueryInterface = require ( "pg-search-sequelize" ) . QueryInterface ;
module . exports = {
up : queryInterface => new QueryInterface ( queryInterface ) . createMaterializedView ( ... ) ,
down : queryInterface => new QueryInterface ( queryInterface ) . dropMaterializedView ( ... ) ,
} ; 두 개의 필드가있는 데이터베이스에서 새로운 구체화 된보기를 만듭니다. 신분증과 문서. 문서 필드는 검색 할 수있는 모든 지정된 속성/필드의 연결 텍스트의 ts_vector 입니다.
name - 구체화 된보기의 이름model - 구체화 된보기를 만들기위한 테이블 모델.attributes - 키 값 쌍 개체는 키가 필드의 이름이고 필드의 값입니다. attributes = {
name : "A" // "A" is the highest weight
description : "B" ,
release_date : "C"
city : "D" // "D" is the lowest possible weight
}options tableName 제공된 경우 통과 된 모델의 tableName 무시합니다.
primaryKeyField 제공된 경우 통과 된 모델의 primaryKeyField 무시합니다.
include - 구체화 된 뷰의 문서에 포함 할 관련 모델의 속성을 정의하는 객체 배열.
include = [
{
model : models . Actor ,
foreignKey : "actor_id" ,
target_key : "id" ,
associationType : "hasMany" ,
attribtues : {
first_name : "C" ,
last_name : "C"
} ,
include : [ ... ] // optionally you can include models associated to the Actor model
} ,
// ...
// Other associated models
]model - 포함 할 모델foreignKey - 관련 모델을 가리키는 외국인. 연관 유형에 따라 외국 키는 참조 모델 (위의 예제의 필름 모델) 또는 다른 모델 (액터 모델)에있을 수 있습니다.targetKey 외국 키가 참조하는 키입니다.associationType 참조 모델 (필름) 관점의 연관 유형. hasOne , hasMany 또는 belongsTo 여야합니다.attributes - 모델에서 포함 할 속성.include - 포함 모델과 관련된 모델 배열 (액터와 관련된 모델) 구체화 된보기를 삭제합니다.
name - 구체화 된보기의 이름