schema.xml 고찰

1. Schema의 정의

- 데이터베이스의 구조와 제약조건에 관한 전반적인 명세를 기술한 것

- 데이터베이스를 구성하는 데이터 개체, 속성, 관계 및 제약조건 등에 관해 전반적으로 정의함

- 스키마는 데이터 사전에 저장되며 메타 데이터라고도 불린다.

2. Solr의 schema.xml (http://wiki.apache.org/solr/SchemaXml)

- The schema.xml file contains all of the details about which fields your documents can contain, and how those fields should be dealt with when adding documents to the index, or when querying those fields.

(schema.xml 파일은 문서가 포함하는 필드들에 관한 상세한 모든 것들을 포함한다. 그리고 색인하거나 필드들을 쿼링할 때 그 필드들이 어떻게 다루어질 것인지도 포함한다.)

- schema.xml은 <schema>태그라는 부모노드로 시작하며 크게 3가지 부분으로 나누어 생각할 수 있다.

<types>태그 부분 / <fields>태그 / 그리고 기타 설정을 위한 태그부분

1) <types>

<fieldtype> 태그의 리스트들을 포함한다. 텍스트, 문자열, 다양한 숫자 타입 등 필요한 모든 기본 타입을 이 영역에 정의한다.

2) <fields>

인덱싱을 위한 필드들을 이 영역에 정의한다.

<field>태그의 속성들

- name : 필드의 이름을 지정

- type : <types>태그 영역에 지정된 기본 타입 중 하나를 지정

- indexed : 색인(indexing)할지 안할지의 여부를 지정. true이면 검색이 가능하며, 정렬이 가능하다.

- stored : 검색하는 동안 값을 되돌려받고 싶다면 true로 지정

- multiValued : 다중값의 허용여부를 지정. true이면 해당 필드는 한 document에서 여러 개의 값을 가질 수 있음.

- required : 필수 입력 사항의 필드라면 true로 지정

- compressed : true이면 gzip을 이용하여 데이터를 압축해서 저장함

<field name="title" type="text_general" indexed="true" stored="true" multiValued="true"/>
<field name="subject" type="text_general" indexed="true" stored="true"/>
<field name="description" type="text_general" indexed="true" stored="true"/>
<field name="comments" type="text_general" indexed="true" stored="true"/>
<field name="author" type="text_general" indexed="true" stored="true"/>
<field name="keywords" type="text_general" indexed="true" stored="true"/>
<field name="category" type="text_general" indexed="true" stored="true"/>
<field name="content_type" type="string" indexed="true" stored="true" multiValued="true"/>
<field name="last_modified" type="date" indexed="true" stored="true"/>
<field name="links" type="string" indexed="true" stored="true" multiValued="true"/>

<dynamicField>

- <field>의 name을 찾지 못했을 경우 dynamicField는 일련의 패턴을 제공하여 찾지 못한 name과 패턴이 매치되는지 확인하고 매치된다면 사용되는 field이다.

<dynamicField name="*_i" type="int" indexed="true" stored="true"/>
<dynamicField name="*_s" type="string" indexed="true" stored="true"/>
<dynamicField name="*_l" type="long" indexed="true" stored="true"/>
<dynamicField name="*_t" type="text_general" indexed="true" stored="true"/>
<dynamicField name="*_txt" type="text_general" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="*_b" type="boolean" indexed="true" stored="true"/>
<dynamicField name="*_f" type="float" indexed="true" stored="true"/>
<dynamicField name="*_d" type="double" indexed="true" stored="true"/>

3) 기타 영역

<uniqueKey> : 고유키 설정하기

고유키로 지정된 필드는 중복된 값이 인덱스에 존재할 없고, 만약 인덱싱 시에 동일한 값이 이미 존재한다면, 오래된 문서에 대한 인덱싱 정보는 삭제되고 새로운 정보가 남게 된다.

<uniqueKey>id</uniqueKey>

<defaultSearchField> : 기본 검색 필드 설정

검색 특정 필드가 지정되지 않은 겨우 기본적으로 검색 대상이 필드를 설정한다.

<defaultSearchField>text</defaultSearchField>

<solrQueryParser> : 검색 연산자 지정

복수개의 단어 검색 적용할 연산자를 설정한다.

(AND -> 모든 단어를 포함, OR –> 하나 이상의 단어를 포함한 컨텐츠 검색)

<solrQueryParser defaultOperator="OR"/>

<copyField> : 멀티 인덱싱 설정

copyField는 하나의 필드를 다른 곳에 복사하고 동시에 document는 색인을 추가한다.

copyField는 같은 필드를 다르게 색인하거나 보다 빠르고 쉬운 검색을 위해 여러개의 필드를 하나의 필드에 추가하기 위해 사용된다.

여러 개의 필드를 하나의 필드처럼 사용해야 경우에 아래와 같이 설정한다.

<copyField source="cat" dest="text"/>
<copyField source="name" dest="text"/>
<copyField source="manu" dest="text"/>
<copyField source="features" dest="text"/>
<copyField source="includes" dest="text"/>
<copyField source="manu" dest="manu_exact"/>

추가내용 - 필터 매핑 설정하기

WEB-INF/web.xml 파일에서 아래처럼 디스패처 필터의 매핑 설정을 추가한다.

<filter>

<filter-name>SolrRequestFilter</filter-name>

<filter-class>org.apache.solr.servlet.SolrDispatchFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>SolrRequestFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

Solr의 indexing과 검색의 작동 절차

- Client로부터 요청이 발생하면 HTTP를 통해 Solr 웹 애플리케이션으로 요청을 넘겨준다.

- 요청을 받으면 Solr는 적합한 SolrRequestHandler를 선택하여 요청을 처리한다.

- 요청 처리 후에 응답을 다시 HTTP로 넘겨준다. (응답의 포맷은 XML과 그 외의 여러가지 형태가 있다)

Solr Index를 업데이트 하기 위한 XML 메세지

- Solr는 XML 메세지로 Add/Replace, Commit, Delete 작업을 수행할 수 있음.

(url/update를 사용해서 => http://localhost:8080/solr/update 처럼..)

- schema.xml과 혼동하지 않도록 주의한다!!

[예시 - Add/Replace를 위한 XML]

<add>
<doc>
<field name="employeeId">05991</field>
<field name="office">Bridgewater</field>
<field name="skills">Perl</field>
<field name="skills">Java</field>
</doc>
[<doc> ... </doc>[<doc> ... </doc>]]
</add>

- <add> 태그의 부수적인 속성들

1) overwrite : 디폴트는 true, true면 새로운 document가 이전의 document를 대신함. 고유키(uniqueKey)는 동일함.

2) commitWithin : document가 추가될 시간을 지정. 밀리세컨드단위로 시간을 지정하면 지정한 시간 내에 document가 추가됨.

[예시 - delete를 위한 XML]

- ID나 Query를 통해서 document를 삭제함.

(ID는 일반적으로 schema에서 정의된 uniqueKey가 되면 본 예시에서는 employeeId가 ID라고 볼 수 있다.)

<delete><id>05991</id></delete>
<delete><query>office:Bridgewater</query></delete>

[update 하기 - cURL을 이용하거나 GET방식을 이용]

- GET방식

http://localhost:8983/solr/update?stream.body=%3Cdelete%3E%3Cquery%3Eoffice:Bridgewater%3C/query%3E%3C/delete%3E
http://localhost:8983/solr/update?stream.body=%3Ccommit/%3E

 

 

출처 : http://blog.naver.com/thooy?Redirect=Log&logNo=10119314104

boost기법이라 하면 검색엔진에서 검색어, 문서, 필드별로 별도의 추가(혹은 감소)가중치를 적용하는 방법을 이야기하며, 이를 가지고 업무환경에 적합한 검색결과를 얻을 수 있도록 하는 것을 말한다.
예를들어 문서의 "제목"은 "본문"보다 가중치를 높게 주어 같은 단어가 제목에서 나온 경우를 우선적으로 보여줄 수 있도록 하는 경우를 말할 수 있을 것이다.

solr는 "색인", "검색"시에 각각의 boost방법들을 제공한다.

  1. 색인시
    • 문서 boosting
      boost = <float> ? default is 1.0
    • 필드 boosting
      boost = <float> ? default is 1.0
       1: <add>
       2:   <doc boost="2.5">
       3:     <field name="employeeId">05991</field>
       4:     <field name="office" boost="2.0">Bridgewater</field>
       5:   </doc>
       6: </add>











    위의 예는 emplyeeId가 05991인 문서에 2.5의 가중치를 주었으며, 이와 동시에 office라는 필드에 2.0의 가중치를 주었다.

  2. 검색시
    • 필드 boosting
      • standard request handler의 경우
        http://localhost:8983/solr/select/?q=title:superman^2+subject:superman
        제목의 superman에 2.0의 가중치를 부여
      • dismax request handler의 경우
        http://localhost:8983/solr/select/?q=superman&qf=title^2+subject
        제목의 superman에 2.0의 가중치를 부여
    • 쿼리(검색어) boosting
      http://localhost:8983/solr/select/?q=title:superman^2
      superman에 2.0의 가중치를 부여
    • Boost 함수
      검색결과의 필드값에 대해 함수를 적용하여 boosting할 수 있도록 지원한다.
      함수에 대한 자세한 설명을 solr 위키를 참조

개인적인 판단은 검색시 boosting하는 방법은 아무래도 실시간으로 연산을 하다보니 검색속도가 느려질 수 있을 것 같다.
대신에 색인시 하는 방법은 속도는 그에 비해 빠를 수 있겠으나, 가중치값이 틀려지게 되면 재색인을 해야 하는 불편함이 있을 것으로 생각된다.
(직접 해 보진 않았음)

 

HTML로 구성된 웹문서를 색인하기 위해서는 기본적으로 HTML테그의 내용을 제거하는 필터링 작업이 필요하다.
solr는 이미 HTMLStripWhitespaceTokenizerFactory라는 HTML의 테그를 제거하고 색인할 수 있는 방법을 제공한다.

schema.xml파일
<
fieldType name="html" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
<tokenizer class="solr.HTMLStripWhitespaceTokenizerFactory" />
</analyzer>
<analyzer type="query">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
</analyzer>
</fieldType>


하지만, 위의 그림과 같이 한글의 경우에는 space단위로 token이 나누어 지기 때문에 CJKTokenizerFactory와 같은 검색결과를 얻을 수가 없다.
하여, solr 1.3에서 새롭게 추가된 NGramFilterFactory를 추가로 이용하여 ngram색인을 해보기로 하였다.
schema.xml파일
<
fieldType name="html" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
<tokenizer class="solr.HTMLStripWhitespaceTokenizerFactory" />
<filter class="solr.NGramFilterFactory" maxGramSize="2" minGramSize="1"/>
</analyzer>
<analyzer type="query">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.NGramFilterFactory" maxGramSize="2" minGramSize="1"/>
</analyzer>
</fieldType>

CJKTokenizerFactory와 같지는 않지만 그런대로 결과는 만족!!!

하지만, 영문도 ngram을 해버리기 때문에 다소 실망하기도 하였다.
(영문까지 ngram처리하면 색인어가 너무 많아짐으로...)


하지만, 이 정도는 (영문은 stemming하도록) solr 소스를 살짝만 바꾸면 아주 쓸만한 색인 환경을 구축할 수 있을 것으로 판단된다.



참고로 query에 WhitespaceTokenizerFactory를 쓴 이유는 보통의 경우라면 검색시에 html테그가 들어갈 일이 없기 때문이다.

 

Importing a MySQL database into Apache Solr Part I

This is a tutorial for getting started with Apache Solr enterprise search with PHP and MySQL on Unix/Linux or Mac OS X. Most of the information I have found is rather incomplete or full of erros so I wanted to share how I have successfully used Solr in a number of different applications. I’m going to break this down into three separate posts/sections.

  • Importing a MySQL database into Apache Solr
  • Using PHP with Apache Solr
  • Using the Suggester feature in the new Apache Solr 3.1

Apaches Solr is an enterprise search application that was developed at CNET and is now part of the Apache Lucene project. It runs in a standalone java servlet contain like Jetty or Tomcat. Since it runs as a webservice, you access it from any application like PHP or in Rails. Results can be returned in XML, JSON, or now CSV format.

There are several advantages to using Solr for your search function in you application. The biggest is speed. In a ~1 gig table Solr will return a result in under 0.2 seconds versus MySql fulltext search which can take up to 10 seconds (or even longer) depending on the length and complexity of the query. End users expect fast search results and Solr can deliver that, while allowing a level of control over search that a person would not be able to achieve using Google, i.e. search for posts by user name or product by manufacturer.

Another big advantage with Solr is that it recognizes plurals and slight misspellings, for instance a query with “Arc’teryx” will return results with both “Acrteryx” and “Arc’teryx”. A description of using other search features like facets can be found at the Solr Homepage.

Where would you use Solr? Any site that has a lot of content will benefit from using enterprise search; large popular blogs, e-commerce sites with a large product database, and forums/message boards.

Server requirements depend on the size of database but are fairly modest while running queries. I have been able to run Solr on a VPS with 300 megs or RAM with laser quick results. However, the database import requires much more RAM, for a 1.5 gig DB it requires at least 2 gigs and preferably 4gig. I don’t believe it’s necessary to run Solr on a separate server or VPS, just making sure that you setup your cron jobs for import to run in the evening when traffic is low.

Let’s get started!

First, all the examples in this tutorial will be run on locally on OS X under the domain solr.local. If you don’t already develop on your machine locally I encourage you to do so. On Mac OS X both MAMP and VirtualHostX are great tools for using a local dev environment.

  1. Start by downloading Solr. The current version is 3.1. Place the directory in an appropriate location, ie User/Sites/Solr31.
  2. In the termimal change into the example directory.
  3. Start the Jetty server up by executing in the terminal “java -jar start.jar.
  4. Get familiar with the terminal output for Jetty as this will help you track down errors later in your configuration.
  5. In your browser go to http://solr.local:8983/solr/admin
  6. Go through the Solr tutorial to get yourself familiar with the feature set.
  7. Stop Jetty with Control-C.

Great. Now we are ready to start getting Solr configured to import your MySQL database. In this example I will be configuring Solr to import a generic message board table.

  1. Download the MySQL JDBC driver from http://www.mysql.com/downloads/connector/j/
  2. Copy the downloaded directory into example/lib
  3. In example/solr/conf create a file called data-config.xml. Change the sql queries to reflect the database you are indexing.
    1. <dataConfig>
    2. <dataSource type="JdbcDataSource"
    3. driver="com.mysql.jdbc.Driver"
    4. url="jdbc:mysql://localhost/ccubbupgrade"
    5. user="root"
    6. password=""/>
    7. <document name="content">
    8. <entity name="id"
    9. query="SELECT
    10. p.post_id,
    11. p.post_posted_time,
    12. FROM_UNIXTIME(p.post_posted_time) AS post_posted_datetime,
    13. p.user_id,
    14. t.forum_id,
    15. p.post_subject,
    16. p.post_default_body
    17. FROM
    18. POSTS AS p
    19. JOIN
    20. TOPICS AS t
    21. ON p.topic_id = t.topic_id
    22. WHERE
    23. p.POST_IS_APPROVED = '1'
    24. AND t.TOPIC_STATUS != 'M'"
    25. deltaImportQuery="SELECT
    26. p.post_id,
    27. p.post_posted_time,
    28. FROM_UNIXTIME(p.post_posted_time) AS post_posted_datetime,
    29. p.user_id,
    30. t.forum_id,
    31. p.post_subject,
    32. p.post_default_body
    33. FROM
    34. POSTS AS p
    35. JOIN
    36. TOPICS AS t
    37. ON p.topic_id = t.topic_id
    38. WHERE
    39. p.post_id = ${dataimporter.delta.post_id}"
    40. deltaQuery="SELECT
    41. post_id
    42. FROM
    43. POSTS
    44. WHERE
    45. post_posted_time > UNIX_TIMESTAMP('${dataimporter.last_index_time}')">
    46. <field column="POST_ID" name="post_id" />
    47. <field column="POST_POSTED_TIME" name="post_posted_time" />
    48. <field column="USER_ID" name="user_id" />
    49. <field column="FORUM_ID" name="forum_id" />
    50. <field column="POST_SUBJECT" name="post_subject" />
    51. <field column="POST_DEFAULT_BODY" name="post_default_body" />
    52. </entity>
    53. </document>
    54. </dataConfig>
  4. We need to tell Solr that we will be using the JDBC driver. Open the solrconfig.xml file in the same directory and insert the following code.
    1. <requestHandler name="/dataimport"
    2. class="org.apache.solr.handler.dataimport.DataImportHandler">
    3. <lst name="defaults">
    4. <str name="config">data-config.xml</str>
    5. </lst>
    6. </requestHandler>
  5. Now we need to add some info into the schema.xml file, located in the same directory, to tell Solr more about our table columns and how to conduct a search.
    1. <!-- Field to use to determine and enforce document uniqueness.
    2. Unless this field is marked with required="false", it will be a required field
    3. -->
    4. <uniqueKey>post_id</uniqueKey>
    5. <field name="post_id" type="string" indexed="true" stored="true" required="true"/>
    6. <field name="post_posted_time" type="tint" indexed="true" stored="true"/>
    7. <field name="user_id" type="int" indexed="true" stored="true" />
    8. <field name="forum_id" type="int" indexed="true" stored="true"/>
    9. <field name="post_subject" type="text" indexed="true" stored="true"/>
    10. <field name="post_default_body" type="text" indexed="true" stored="true"/>
    11. <!-- field for the QueryParser to use when an explicit fieldname is absent -->
    12. <defaultSearchField>fulltext</defaultSearchField>
  6. Go ahead and start Jetty up again with “java -jar start.jar” and check for any errors in the terminal.
  7. Now it’s time to do a full index. In your browser go to http://solr.local:8983/solr/dataimport?command=full-import . This process will take a while depending on the size of your database. Check the status of the import with http://solr.local:8983/solr/dataimport . The response format will look like this for the first little bit “00data-config.xmlidleThis response format is experimental. It is likely to change in the future.” Eventually it will show you the index progress after it has loaded the database.
  8. After the index process is done you should be able to search your data at http://solr.local:8983/solr/admin . If not, look at the errors popping up in the terminal. Results will be in XML format.
  9. To setup delta indexing (ie changes made every hour or interval at you choosing) setup a cronjob to the following url http://solr.local:8983/solr/dataimport?command=delta-import
  10. To run the Solr service in the background or in the background on your server make sure you start it like this “java -jar start.jar &”

In another post I will cover locking down Solr so that it is only accessible by IP address or username/password combo.

 

출처 : http://entropytc.com/importing-a-mysql-database-into-apache-solr/#codesyntax_1

Solr

Lucene을 Java API가 아닌 HTTP 호출을 통해서 사용할 수 있게 만든 서비스.

  • 때문에 모든 언어에서 Solr를 통해 Lucene을 사용하는 것이 가능해지고,
  • 여러 WAS에서 Solr 단일 인스턴스에 검색/인덱싱 가능.(확장성이 좋아진다)
  • 기본적으로 모든 요청과 응답은 HTTP GET/POST 를 통해서 XML로 이루어 진다.
  • "솔라"

언어별 응답

응답을 받을 때는 각 언어별로, 언어별 데이터 형으로 받는 것이 가능하다. 또한 언어별 Client 라이브러리가 제공된다.

  • JSON
  • Python : 2007년 6월 말 현재, Solr 1.2와 호환 안되는 상태임. 확인할 것. 살짝 고치면 잘 작동함.
  • Ruby
  • Java의 경우에는 example을 확인할것.

한글 처리

한글 검색을 위해서는 CJKTokenizer를 사용해야 하는데, 현재 Solr 1.2에는 CJKTokenizerFactory가 들어있지 않다.

  • CJKTokenizerFactory.java : 링크 아래 파일을 컴파일하여 Solr WEB-INF/classes 에 넣어주고 재시작 한다.
  1. package org.apache.solr.analysis;

    import java.io.Reader;
    import org.apache.lucene.analysis.cjk.CJKTokenizer ;
    import org.apache.lucene.analysis.TokenStream;
    import org.apache.solr.analysis.BaseTokenizerFactory;

    /**
    * CJKTokenizer for Solr
    * @see org.apache.lucene.analysis.cjk.CJKTokenizer
    * @author matsu
    */
    public class CJKTokenizerFactory extends BaseTokenizerFactory {

    /**
    * @see org.apache.solr.analysis.TokenizerFactory#create(Reader)
    */
    public TokenStream create(Reader input) {
    return new CJKTokenizer( input );
    }
    }
  • Tokenizer Factory를 인덱싱이 필요한 FieldType에 추가하고, Filter로 StopFilterFactory와 WordDelimiterFilterFactory 를 추가해줘야 한다.
  1. <fieldType name="text" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
    <tokenizer class="solr.CJKTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt"/>
    <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0"/>
    </analyzer>
    <analyzer type="query">
    <tokenizer class="solr.CJKTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt"/>
    <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0"/>
    </analyzer>
    </fieldType>

출처 : http://kwon37xi.springnote.com/pages/335478

1)
두개의 디렉토리 생성
C:\TOMCAT_HOME
C:\SOLR_HOME

2) 톰캣 부터 설정
C:\TOMCAT_HOME 에 톰캣 압축을 푼다.
C:\TOMCAT_HOME\conf\Catalina\localhost 디렉토리 생성함
C:\TOMCAT_HOME\conf\Catalina\localhost
C:\TOMCAT_HOME\conf\Catalina\localhost\solr.xml 파일을 만듬
내용은

<Context docBase=”C:\SOLR_HOME\solr-1.4.0.war” debug=”0″ crossContext=”true” >
<Environment name=”solr/home” type=”java.lang.String” value=”C:\SOLR_HOME\solr” override=”true” />
< /Context>

보통 C:\TOMCAT_HOME\bin\solr\data\index 여기에 인덱스가 생성됨

C:\TOMCAT_HOME\bin\startup.bat shutdown.bat로 톰캣을 띄워봄

localhost:8080

3) Solr 설정
솔라 압축푼 파일 중

apache-solr-1.4.0\example\solr 폴더를 C:\SOLR_HOME 에 복사함.

bin 과 conf 폴더인데 Environment name=”solr/home” 으로 지정된 폴더에서 conf를 찾으므로 필수임

\apache-solr-1.4.0\dist\apache-solr-1.4.0.war 을 C:\SOLR_HOME 에 복사 해둠

4) War를 다시 구성할 경우

WEB-INF\lib에 추가를 하거나 소스가 변경되었을시 war를 다시 생성해야함.

C:\SOLR_HOME\apache-solr-1.4.0>jar -cvf ../solr-1.4.0.war *

5) 데이터 테스트 전송

Solr 원본에 있는 example\exampledocs 파일을 이용해서 올려 보자

C:\SOLR_HOME\apache-solr-1.4.0\ example\exampledocs>java -Durl=http://localhost:8080/solr/update -jar *.xml

6) 한글 문제

먼저 톰캣 설정

C:\TOMCAT_HOME\conf\Server.xml

<Connector port=”8080″ protocol=”HTTP/1.1″
connectionTimeout=”20000″ URIEncoding=”UTF-8″
redirectPort=”8443″ />

C:\SOLR_HOME\apache-solr-1.4.0\WEB-INF\lib 에

최신 koreananalyzer-20100525.jar 한글 분석기를 넣음

C:\SOLR_HOME\apache-solr-1.4.0\WEB-INF\classes

를 생성하고 다음 두개 파일을 만듬

A) KoreanFilterFactory.java

package org.apache.solr.analysis;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.kr.KoreanFilter;

public class KoreanFilterFactory extends BaseTokenFilterFactory {
private boolean bigrammable=true;
private boolean hasOrigin=true;

public TokenStream create(TokenStream tokenstream) {
return new KoreanFilter(tokenstream,bigrammable,hasOrigin);
}
public void setBigrammable(boolean bool){
this.bigrammable=bool;
}
public void setHasOrigin(boolean bool) {
this.hasOrigin=bool;
}
}

B) KoreanTokenizerFactory.java

package org.apache.solr.analysis;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.kr.KoreanFilter;

public class KoreanFilterFactory extends BaseTokenFilterFactory {
private boolean bigrammable=true;
private boolean hasOrigin=true;

public TokenStream create(TokenStream tokenstream) {
return new KoreanFilter(tokenstream,bigrammable,hasOrigin);
}
public void setBigrammable(boolean bool){
this.bigrammable=bool;
}
public void setHasOrigin(boolean bool) {
this.hasOrigin=bool;
}
}

컴파일 방법

c:\SOLR_HOME\apache-solr-1.4.0\WEB-INF\classes>javac -cp ..\lib\lucene-analyzers
-2.9.1.jar;..\lib\lucene-core-2.9.4.jar;..\lib\apache-solr-core-1.4.0.jar;..\lib
\koreananalyzer-20100525.jar -d . *.java

War로 다시 압축하고

톰캣 리스타트..한글 잘됨

테스트 데이터 넣어보기

c:\SOLR_HOME\exampledocs>java -Durl=http://localhost:8080/solr/update -jar post.
jar hd.xml

기본은 8393 포트인가를 찾는다 포트를 지정해서 가려면 -Durl을 쓴다.

 

 

출처 : http://ofwww.com/

[시작하기]
1. solr 최신버전 다운

2. example디렉토리로 이동해서 Solr 서버를 실행
Jetty가 8983 port로 실행된다.
$ cd example
$ example$ java -jar start.jar
>java -jar start.jar
2012-04-16 14:35:38.691:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
2012-04-16 14:35:38.803:INFO::jetty-6.1-SNAPSHOT
2012-04-16 14:35:38.830:INFO::Started SocketConnector@0.0.0.0:8983

3. 웹브라우져에서 접속(http://localhost:8983/solr/admin/)을 확인한다.


[색인 테스트]
1. example\exampledocs로 이동해서 post.jar 파일을 이용해서 색인
example\exampledocs$ java -jar post.jar solr.xml monitor.xml
SimplePostTool: version 1.4
SimplePostTool: POSTing files to http://localhost:8983/solr/update..
SimplePostTool: POSTing file solr.xml
SimplePostTool: POSTing file monitor.xml
SimplePostTool: COMMITting Solr index changes..

2. 다음과 같이 검색 URL로 색인 결과를 확인
http://localhost:8983/solr/select/?q=solr&start=0&rows=10&indent=on


3. 색인 데이터에 대한 통계치 보기
http://localhost:8983/solr/admin/stats.jsp
다음과 같이 현재까지 17개의 문서가 색인되어 있음을 알 수 있다.


4. 색인데이터 삭제하기
다음과 같이 schema.xml에 설정된 uniqueKey를 가진 필드를 지정하여 해당 문서를 색인결과에서 삭제할 수 있다.
example\exampledocs$ java -Ddata=args -Dcommit=no -jar post.jar “SP2514N”

example\exampledocs$ java -Ddata=args -Dcommit=no -jar post.jar “SP2514N”
위와 같이 삭제가 될 것이라는 메시지를 확인할 수 있고,

example\exampledocs$ java -jar post.jar 명령어를 날려 삭제에 대한 반영(commit)을 한다.



[검색 테스트]
1. 파라미터에 의해서 HTTP GET 방식으로 검색
쿼리파라미터의 예) http://localhost:8983/solr/select/?q=id:SOLR1000&fl=id+name
q=SOLR1000&fl=name,id (기본 검색필드에서 ‘SOLR1000′를 검색하고, name과 id만 return 받음)
q=id:SOLR1000&fl=name,id,score (id필드에서 ‘SOLR1000′를 검색하고, name, id와 score를 return 받음)
q=id:SOLR1000&fl=*,score (stored=yes인 모든 필드와 score를 return 받음)
q=id:SOLR1000&sort=price desc&fl=name,id,price (price필드로 내림차순 정렬된 결과를 받음)
q=id:SOLR1000&wt=json (JSON 포맷으로 결과를 받음)

2. 검색결과 하이라이팅
검색과 마찬가지로 검색파라미터에 ‘hl’ 파라미터를 추가하여 강조 (for emphasis) tags를 추가한다.
q=id:SOLR1000&fl=id,name&hl=true&hl.fl=id
–> 검색결과에 대해서 하이라이팅 시키고, 그 필드는 name를 대상으로 한다.


3. Faceted Search (group by 검색)
이 기능은 group by 검색과 유사할 것 같다.
예1) q=*:*&facet=true&facet.field=popularity (모든 결과에 대해서 popularity값에 적용하다.)

예2) q=*:*&facet=true&facet.field=popularity&facet.field=price

예3) q=*:*&facet=true&facet.query=price:[50 TO 300]&facet.query=popularity:[7 TO *]

예4)q=*:*&facet=true&facet.date=manufacturedate_dt&facet.date.start=2004-01-1T00:00:00Z&facet.date.end=2010-01-01T00:00:00Z&facet.date.gap=+1YEAR

날짜를 범위로 검색한다. 2004년부터 2010년까지의 결과를 검색한다.

 

출처 : http://ncue.tistory.com/

버젼이 0.9.7 릴되고 사용한건데
운영하고 있는 서버에서 테스트해보면 여전히 속도는 최상이네요.

이번에 새로운 서버 만들어서 2.0.3 RPM버젼 설치했는데..
아래 설정으로 한글 검색 되고요..
근데 결과가 과거버젼하고는 많이 다른 느낌이네요.

"학교"를 검색해보니... "학" 와 "교"를 가져오네요.
공부좀 더 해봐야겠어요.
일단 rt 기능이 좋더군요. dump파일을 mysql h 0 P 포트 < dump.sql 로 입력해버리고
실시간 검색이 가능하더군요. 리부팅 시켜도 자료가 사라지는 것이 아니라 유지되고
일단 테스트해 볼 가치는 있는 것 같아요.

centos 에서 rpm으로 sphinx설치하게되면 php에서 모듈로 바로 사용되네요..

+ Recent posts