Node.js 용 SphinxQL Query Builder는 TypeScript로 썼습니다. 원시 sphinxql 문자열을 항상 작성하는 것을 피하는 쉬운 쿼리를 만들 수 있습니다. 기본적으로, 그것은 항상 보안에서 생각하는 이스케이프 쿼리 매개 변수를 사용합니다.
그것은 PHP SphinxQL-Query-Builder와 Eloquent Query Builder (Laravel Framework ORM)에서 크게 영감을 받았습니다.
Create Connection에 사용되는 클라이언트는 성능에 중점을 둔 MySQL2입니다.
node.js> = 6.x를 사용해야합니다
NPM 명령을 실행합니다.
npm install --save sphinxql간단한 연결을 만들려면 (가장 권장되지 않은 것이 아니라 풀 연결을 사용하십시오) 첫 번째 쿼리를 작성하려면 다음과 같이하십시오.
const { Sphinxql , Expression } = require ( 'sphinxql' ) ;
const sphql = Sphinxql . createConnection ( {
host : 'localhost' ,
port : 9306
} ) ;
sphql . getQueryBuilder ( )
. select ( '*' )
. from ( 'books' )
. match ( 'title' , 'harry potter' )
. where ( 'created_at' , '<' , Expression . raw ( 'YEAR()' ) )
. between ( Expression . raw ( `YEAR(created_at)` ) , 2014 , 2019 )
. orderBy ( { 'date_published' : 'ASC' , 'price' : 'DESC' } )
. limit ( 10 )
. execute ( )
. then ( ( result , fields ) => {
console . log ( result ) ;
} )
. catch ( err => {
console . log ( err ) ;
} ) ; 응용 프로그램과 Manticore/Sphinx 서버간에 연결을 만드는 두 가지 가능한 방법이 있습니다. 가장 먼저 간단한 것은 createConnection 메소드를 사용하는 것입니다.
const { Sphinxql } = require ( 'sphinxql' ) ;
const sphql = Sphinxql . createConnection ( {
host : 'localhost' ,
port : 9306
} ) ; 두 번째 옵션은 createPoolConnection 메소드를 사용하는 것입니다. 이 방법론을 사용하면 Manticore/Sphinx와 이전 연결을 재사용하는 여러 가지 개방형 연결을 가질 수 있습니다. MySQL2 연결 풀 (풀 생성 및 구성에 허용되는 매개 변수)에 대한 자세한 내용은 연결 풀 사용에 대한 MySQL2 문서를 읽으십시오. 이 기술은 더 많은 메모리를 사용하므로 알아야합니다.
const { Sphinxql } = require ( 'sphinxql' ) ;
// Create the connection pool. The pool-specific settings are the defaults
const sphql = Sphinxql . createPoolConnection ( {
host : 'localhost' ,
port : 9306 ,
waitForConnections : true ,
connectionLimit : 10 ,
queueLimit : 0
} ) ;이 섹션은 여러 부분에서 분리되어 있지만 이전에 SphinXQL을 사용했거나 SQL을 사용한 경우이 섹션도 매우 기본적으로 볼 수 있습니다. 어쨌든 나는이 API를 사용하는 방법에 대한 좋은 아이디어를 얻기 위해 Manticore Search 또는 Sphinx 문서를 강력하게 읽는 것이 좋습니다.
여기서 예 :
sphql . getQueryBuilder ( )
. select ( 'id' , 'author_id' , 'publication_date' )
. from ( 'books' )
. match ( '*' , '"harry potter"' , false )
. whereIn ( 'lang' , [ 'en' , 'sp' , 'fr' ] )
. between ( Expression . raw ( `YEAR(publication_date)` ) , 2008 , 2015 )
. execute ( )
. then ( ( result , fields ) => {
console . log ( result ) ;
} )
. catch ( err => {
console . log ( err ) ;
} ) ; 메소드 "옵션"을 사용하여 여러 옵션을 체인 할 수 있습니다. 메소드 헤드는 다음과 같습니다.
옵션이있는 예 :
sphql . getQueryBuilder ( )
. select ( 'id' , 'author_id' , 'publication_date' )
. from ( 'books' )
. match ( '*' , '"harry potter"' , false )
. between ( Expression . raw ( `YEAR(publication_date)` ) , 2008 , 2015 )
. orderBy ( { 'publication_date' : 'ASC' , 'price' : 'DESC' } )
. limit ( 10 )
. option ( 'rank_fields' , 'title content' )
. option ( 'field_weights' , { title : 100 , content : 1 } )
. execute ( )
. then ( ( result , fields ) => {
console . log ( result ) ;
} )
. catch ( err => {
console . log ( err ) ;
} ) ; // TODO
삽입 문은 다음과 같이 생성됩니다.
const document = {
id : 1 ,
content : 'this is the first post for the blog...' ,
title : 'First post'
} ;
connection . getQueryBuilder ( )
. insert ( 'my_rtindex' , document )
. execute ( )
. then ( ( result , fields ) => {
console . log ( result ) ;
} )
. catch ( err => {
console . log ( err ) ;
} ) ;또는 동일한 쿼리에 여러 값을 삽입하기 위해 키 값 쌍의 배열을 사용합니다.
const document = [ {
id : 1 ,
content : 'this is the first post for the blog...' ,
title : 'First post'
} , {
id : 2 ,
content : 'this is the second post for the blog...' ,
title : 'Second post'
} ] ;
connection . getQueryBuilder ( )
. insert ( 'my_rtindex' , document )
. execute ( )
. then ( ( result ) => {
console . log ( result ) ;
} )
. catch ( err => {
console . log ( err ) ;
} ) ;Doc ID 또는 삽입물을 사용하여 문서를 대체합니다. 삽입 문과 유사하게 교체 용 삽입을 변경합니다.
const document = {
id : 1 ,
content : 'this is the first post for the blog...' ,
title : 'UPDATE! First post'
} ;
connection . getQueryBuilder ( )
. replace ( 'my_rtindex' , document )
. execute ( )
. then ( ( result ) => {
console . log ( result ) ;
} )
. catch ( err => {
console . log ( err ) ;
} ) ; const document = {
content : 'UPDATE! it's an old post. this is the first post for the blog...' ,
title : 'First post (edit)'
} ;
connection . getQueryBuilder ( )
. update ( 'my_rtindex' )
. set ( document )
. match ( 'fullname' , 'John' )
. where ( 'salary' , '<' , 3000 )
. execute ( )
. then ( ( result , fields ) => {
console . log ( result ) ;
} )
. catch ( err => {
console . log ( err ) ;
} ) ;이 패키지는 또한 거래 지원이 제공됩니다. 트랜잭션은 RT 인덱스에만 사용할 수 있습니다. 자세한 내용은 Manticore 검색을 위해 거래 문서를 방문하십시오.
트랜잭션 API는 간단하고 방법 목록은 다음과 같습니다.
이 모든 방법은 약속 객체를 반환합니다.
트랜잭션으로 작업하는 간단한 예 :
const document = {
id : 1 ,
content : 'this is the first post for the blog...' ,
title : 'First post'
} ;
const insertDocumentAndCommit = async ( doc ) => {
await connection . getQueryBuilder ( ) . transaction . begin ( ) ;
connection . getQueryBuilder ( )
. insert ( 'my_rtindex' , doc )
. execute ( )
. then ( ( result , fields ) => {
console . log ( result ) ;
} )
. catch ( err => {
console . log ( err ) ;
} ) ;
await connection . getQueryBuilder ( ) . transaction . commit ( ) ;
return true ;
}
insertDocumentAndCommit ( document ) ;우선 Manticore/Sphinx에서 다중 쿼리의 한계를 알아야합니다. Manticore Search and Sphinx Documentation에 따르면 배치에 사용 된 다음 진술에 대한 지원은 다음과 같습니다.
이것을 말하면, 이제 코드를 작성하는 순간입니다. 필요한 방법만을 구현하는 클래스, 큐가 있으며, 멀티 쿼리를 실행하는 것이 유용합니다. 다중 문을 활성화하려면 연결 생성을 위해 구성 객체에 Multiplestatements : True : 다음과 같이 지정해야합니다.
const { Sphinxql } = require ( 'sphinxql' ) ;
const sphql = Sphinxql . createConnection ( {
host : 'localhost' ,
port : 9306 ,
multipleStatements : true
} ) ;이제 대기열을 만들고 처리하겠습니다.
const { Queue , Sphinxql } = require ( 'sphinxql' ) ;
const sphql = Sphinxql . createConnection ( {
host : 'localhost' ,
port : 9306 ,
multipleStatements : true
} ) ;
const queue = new Queue ( sphql . getConnection ( ) ) ;
queue
. push ( sphql . getQueryBuilder ( ) . select ( '*' ) . from ( 'rt' ) . where ( 'id' , '=' , 1 ) )
. push (
sphql . getQueryBuilder ( )
. select ( 'id' , 'author_id' , 'publication_date' )
. from ( 'books' )
. match ( '*' , '"harry potter"' , false )
) ;
queue . process ( )
. then ( results => {
console . log ( results . results . length ) // 2
} )
. catch ( err => console . log ( err ) ) ;이 명령문을 사용하려면 Manticore Documantation의 첨부 인덱스에 대해 읽으십시오. 아래 예제를 참조하십시오.
connection . getQueryBuilder ( )
. attachIndex ( 'my_disk_index' )
. to ( 'my_rt_index' )
. withTruncate ( ) // this method is optional
. execute ( )
. then ( ( result , fields ) => {
console . log ( result ) ;
} )
. catch ( err => {
console . log ( err ) ;
} ) ; 이 명령문을 사용하려면 플러시 rtindex에 대해 읽으십시오.
connection . getQueryBuilder ( )
. flushRTIndex ( 'my_rt_index' )
. execute ( )
. then ( ( result , fields ) => {
console . log ( result ) ;
} )
. catch ( err => {
console . log ( err ) ;
} ) ; Manticore Documantation에서 Truncate rtindex에 대해 읽으려면이 진술을 사용하려면 아래 예를 참조하십시오.
connection . getQueryBuilder ( )
. truncate ( 'my_rt_index' )
. withReconfigure ( ) // this method is optional
. execute ( )
. then ( ( result , fields ) => {
console . log ( result ) ;
} )
. catch ( err => {
console . log ( err ) ;
} ) ; 이 진술을 사용하려면 Manticore Documantation의 Reload Index에 대해 읽으십시오.
connection . getQueryBuilder ( )
. reloadIndex ( 'my_index' )
. from ( '/home/mighty/new_index_files' ) // this method is optional
. then ( ( result , fields ) => {
console . log ( result ) ;
} )
. catch ( err => {
console . log ( err ) ;
} ) ;호출 GetQueryBuilder 메서드 후 사용 가능한 쿼리 메소드를 사용하여 원시 쿼리를 실행하십시오. 이 방법은 a를 사용하여 준비 된 명령문을 허용합니다. (물음) 값을 피하고 싶은 곳.
connection . getQueryBuilder ( )
. query ( `SELECT * FROM sales WHERE MATCH(@title "italian lamp") AND tags IN (?, ?)` , [ 'home' , 'italian style' ] )
. then ( ( result , fields ) => {
console . log ( result ) ;
} )
. catch ( err => {
console . log ( err ) ;
} ) ; 모든 진술에는 내부적으로 쿼리를 실행하는 데 사용되는 최종 방법이 있습니다. 이 메소드는 Generate ()를 사용하여 외부에서 사용할 수 있으며 최종 쿼리와 함께 문자열을 반환합니다.
const sphinxqlQuery = connection . getQueryBuilder ( )
. select ( 'user_id' , 'product_id' , Expression . raw ( 'SUM(product_price) as total' ) . getExpression ( ) )
. from ( 'rt_sales' )
. facet ( ( f ) => {
return f
. fields ( [ 'category_id' ] )
. by ( [ 'category_id' ] )
} )
. facet ( ( f ) => {
return f
. field ( 'brand_id' )
. orderBy ( Expression . raw ( 'facet()' ) )
. limit ( 5 )
} )
. generate ( ) ;
console . log ( sphinxqlQuery ) ; // SELECT user_id, product_id, SUM(product_price) as total FROM rt_sales FACET category_id BY category_id FACET brand_id ORDER BY facet() DESC LIMIT 5