1. 程式人生 > >分散式搜尋Elasticsearch——QueryBuilders.matchPhrasePrefixQuery

分散式搜尋Elasticsearch——QueryBuilders.matchPhrasePrefixQuery

        ES源代碼中對matchPhrasePrefixQuery的描述如下所示:

    /**
     * Creates a match query with type "PHRASE_PREFIX" for the provided field name and text.
     *
     * @param name The field name.
     * @param text The query text (to be analyzed).
     */
    public static MatchQueryBuilder matchPhrasePrefixQuery(String name, Object text) {
        return new MatchQueryBuilder(name, text).type(MatchQueryBuilder.Type.PHRASE_PREFIX);
    }

       如果你呼叫matchPhrasePrefixQuery時,text為中文,那麼,很大可能是一種狀況:你會發現,matchPhraseQuery和matchPhrasePrefixQuery沒有任何差別。而當text為英文時,差別就顯現出來了:matchPhraseQuery的text是一個英文單詞,而matchPhrasePrefixQuery的text則無這一約束,你可以從一個英文單詞中抽幾個連線在一起的字母進行查詢。

        示例程式碼如下所示:

/**
 * @author Geloin
 */
package com.gsoft.gsearch.util;

import java.util.UUID;

import junit.framework.Assert;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.junit.Test;

import com.gsoft.gsearch.BaseTest;
import com.gsoft.gsearch.entity.Person;

/**
 * 以短語形式查詢,查詢時關鍵字不會被分詞,而是直接以一個字串的形式查詢
 * 
 * @author Geloin
 * 
 */
public class MatchPhrasePrefixQueryTest extends BaseTest {
	
	@Test
	public void matchPhrasePrefixQuery() {
		try {
			
			// 建立索引
			BulkRequestBuilder builder = client.prepareBulk();

			for (int i = 0; i < 2; i++) {
				Person p = new Person();
				p.setId(UUID.randomUUID().toString());
				p.setAge(20);
				p.setIsStudent(false);
				p.setSex("男");
				p.setName("Zhangsan wang");

				String source = ElasticSearchUtil.BeanToJson(p);

				IndexRequest request = client.prepareIndex().setIndex(index)
						.setType(type).setId(p.getId()).setSource(source)
						.request();

				builder.add(request);
			}

			BulkResponse bResponse = builder.execute().actionGet();
			if (bResponse.hasFailures()) {
				Assert.fail("建立索引出錯!");
			}

			// 檢索
			QueryBuilder qb = QueryBuilders.matchPhraseQuery("name", "wa");
			
			SearchResponse searchResponse = client.prepareSearch(index)
					.setTypes(type).setQuery(qb).setFrom(0).setSize(12)
					.execute().actionGet();

			SearchHits hits = searchResponse.getHits();
			if (null == hits || hits.totalHits() == 0) {
				log.error("使用matchPhraseQuery(\"name\", \"wa
\")沒有查詢到任何結果!"); } else { for (SearchHit hit : hits) { String json = hit.getSourceAsString(); Person newPerson = mapper.readValue(json, Person.class); System.out.println("name\t\t" + newPerson.getName()); System.out.println("sex\t\t" + newPerson.getSex()); System.out.println("age\t\t" + newPerson.getAge()); System.out.println("isStudent\t\t" + newPerson.getIsStudent()); } } System.out.println("==================================================="); // 檢索 QueryBuilder qb1 = QueryBuilders.matchPhrasePrefixQuery("name", "wa"); SearchResponse searchResponse1 = client.prepareSearch(index) .setTypes(type).setQuery(qb1).setFrom(0).setSize(20) .execute().actionGet(); SearchHits hits1 = searchResponse1.getHits(); if (null == hits1 || hits1.totalHits() == 0) { log.error("使用matchPhrasePrefixQuery(\"name\", \"wa\")沒有查詢到任何結果!"); return; } else { for (SearchHit hit : hits1) { String json = hit.getSourceAsString(); Person newPerson = mapper.readValue(json, Person.class); System.out.println("name\t\t" + newPerson.getName()); System.out.println("sex\t\t" + newPerson.getSex()); System.out.println("age\t\t" + newPerson.getAge()); System.out.println("isStudent\t\t" + newPerson.getIsStudent()); } } } catch (Exception e) { e.printStackTrace(); } finally { if (null != client) { client.close(); } if (null != node) { node.close(); } } } }
        你會發現,使用matchPhraseQuery並未查詢出結果,而matchPhrasePrefixQuery查詢出的,則是我們需要的結果。