分布式搜索Elasticsearch——QueryBuilders.termQuery

         注:该文项目基础为分布式搜索Elasticsearch——项目过程(一)和分布式搜索Elasticsearch——项目过程(二),项目骨架可至这里下载。

        ES源代码中对termQuery的描述如下所示:

    /**
     * A Query that matches documents containing a term.
     *
     * @param name  The name of the field
     * @param value The value of the term
     */
    public static TermQueryBuilder termQuery(String name, String value) {
        return new TermQueryBuilder(name, value);
    }

        termQuery是我花了较多时间才了解的一种Query(因之前对Lucene的研究较少),经总结发现,termQuery 中的value有以下情况:

        1. 若value为汉字,则大部分情况下,只能为一个汉字;

        2. 若value为英文,则是一个单词;

        termQuery代码如下所示:

/**
 * @author Geloin
 */
package com.geloin.esample.util;

import java.util.UUID;

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.fasterxml.jackson.databind.ObjectMapper;
import com.geloin.esample.BaseTest;
import com.geloin.esample.entity.Person;

/**
 * @author Geloin
 * 
 */
public class TermQueryTest extends BaseTest {

	@Test
	public void termQuery() {
		String index = "user";
		String type = "tb_person";
		try {
			// 创建索引
			Person p = new Person();
			p.setId(UUID.randomUUID().toString());
			p.setAge(20);
			p.setIsStudent(false);
			p.setSex("男");
			p.setName("别克");

			ObjectMapper mapper = new ObjectMapper();
			String source = mapper.writeValueAsString(p);

			client.prepareIndex(index, type, p.getId()).setSource(source)
					.execute().actionGet();

			// 查询
			QueryBuilder qb = QueryBuilders.termQuery("name", "别");

			SearchResponse sResponse = client.prepareSearch(index)
					.setTypes(type).setQuery(qb).setFrom(0).setSize(12)
					.execute().actionGet();
			SearchHits hits = sResponse.getHits();

			if (null != hits && hits.totalHits() > 0) {
				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());
				}
			} else {
				log.info("没有查询到任何结果!");
			}

			// 防止出现:远程主机强迫关闭了一个现有的连接
			Thread.sleep(100000);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}


你可能感兴趣的:(Elasticsearch)