programing

MongoDB 2.4의 Meteor 앱에서 전체 텍스트 검색 구현

bestprogram 2023. 5. 27. 12:03

MongoDB 2.4의 Meteor 앱에서 전체 텍스트 검색 구현

Meteor 앱에 전체 텍스트 검색을 추가하는 것을 검토 중입니다.MongoDB가 현재 이 기능을 지원한다는 것은 알고 있지만 구현에 대해 몇 가지 질문이 있습니다.

  • 텍스트 검색 기능을 활성화하는 가장 좋은 방법은 무엇입니까?textSearchEnabled=trueMeteor 앱에서?
  • 인덱스를 추가할 수 있는 방법이 있습니까?db.collection.ensureIndex()앱 내에서?
  • 어떻게 Mongo 명령을 실행할 수 있습니까?db.quotes.runCommand( "text", { search: "TOMORROW" } )Meteor 앱 내에서?

제 목표가 망원경에 검색을 추가하는 것이기 때문에 최소한의 명령줄 마법이 필요하고 Heroku 또는 *.meteor.com 에서도 작동할 수 있는 "플러그 앤 플레이" 구현을 찾고 있습니다.

유성 코드를 편집하지 않는 가장 간단한 방법은 자신만의 mongodb를 사용하는 것입니다.당신의.mongodb.conf이와 같이 보여야 합니다(Arch Linux의 경우)./etc/mongodb.conf)

bind_ip = 127.0.0.1
quiet = true
dbpath = /var/lib/mongodb
logpath = /var/log/mongodb/mongod.log
logappend = true
setParameter = textSearchEnabled=true

핵심 라인은.setParameter = textSearchEnabled=true문자 검색을 가능하게 합니다.

시작mongod업.

유성에게 사용하라고 합니다.mongod지정함으로써 자체가 아닙니다.MONGO_URL환경 변수

MONGO_URL="mongodb://localhost:27017/meteor" meteor

이제 당신에게 전화한 컬렉션이 있다고 말합니다.Dinosaurs에 있어서의 선언된 발언권.collections/dinosaurs.js

Dinosaurs = new Meteor.Collection('dinosaurs');

집합에 대한 텍스트 색인을 만들려면 파일을 작성합니다.server/indexes.js

Meteor.startUp(function () {
    search_index_name = 'whatever_you_want_to_call_it_less_than_128_characters'

    // Remove old indexes as you can only have one text index and if you add 
    // more fields to your index then you will need to recreate it.
    Dinosaurs._dropIndex(search_index_name);

    Dinosaurs._ensureIndex({
        species: 'text',
        favouriteFood: 'text'
    }, {
        name: search_index_name
    });
});

그러면 다음을 통해 검색을 노출할 수 있습니다.Meteor.method예를 들어 파일에server/lib/search_dinosaurs.js.

// Actual text search function
_searchDinosaurs = function (searchText) {
    var Future = Npm.require('fibers/future');
    var future = new Future();
    Meteor._RemoteCollectionDriver.mongo.db.executeDbCommand({
        text: 'dinosaurs',
        search: searchText,
        project: {
          id: 1 // Only take the ids
        }
     }
     , function(error, results) {
        if (results && results.documents[0].ok === 1) {
            future.ret(results.documents[0].results);
        }
        else {
            future.ret('');
        }
    });
    return future.wait();
};

// Helper that extracts the ids from the search results
searchDinosaurs = function (searchText) {
    if (searchText && searchText !== '') {
        var searchResults = _searchEnquiries(searchText);
        var ids = [];
        for (var i = 0; i < searchResults.length; i++) {
            ids.push(searchResults[i].obj._id);
        }
        return ids;
    }
};

그러면 'server/publications.js'에서 검색된 문서만 게시할 수 있습니다.

Meteor.publish('dinosaurs', function(searchText) {
    var doc = {};
    var dinosaurIds = searchDinosaurs(searchText);
    if (dinosaurIds) {
        doc._id = {
            $in: dinosaurIds
        };
    }
    return Dinosaurs.find(doc);
});

그리고 고객측 구독은 다음과 같이 보일 것입니다.client/main.js

Meteor.subscribe('dinosaurs', Session.get('searchQuery'));

음악 크롤러 프로젝트가 대부분의 지식의 원천이었던 티모 브링크만의 소품.

텍스트 색인을 만들고 이렇게 추가하려고 시도하는 것은 여전히 문제 의견이 있다면 유용할 것입니다.

docs.mongodb.org 에서:


사용자 이름에 오름차순 색인 키를 지정하는 다음 예제와 같이 스칼라 색인 필드를 텍스트 색인에 추가합니다.

db.collection.ensureIndex( { comments: "text",
                             username: 1 } )

경고 다중 키 인덱스 필드 또는 지리공간 인덱스 필드를 포함할 수 없습니다.

다음과 같이 인덱스의 필드만 반환하려면 텍스트의 프로젝트 옵션을 사용합니다.

db.quotes.runCommand( "text", { search: "tomorrow",
                                project: { username: 1,
                                           _id: 0
                                         }
                              }
                    )

참고: 기본적으로 _id 필드는 결과 집합에 포함됩니다.예제 인덱스에 _id 필드가 포함되어 있지 않으므로 프로젝트 문서에서 해당 필드를 명시적으로 제외해야 합니다.

언급URL : https://stackoverflow.com/questions/17159626/implementing-mongodb-2-4s-full-text-search-in-a-meteor-app