# 对汽车品牌进行全文检索、精准查询和前缀搜索

为了查询,再插入一条数据

PUT /car_shop/cars/5
{
    "brand": "华晨宝马",
    "name": "宝马318",
    "price": 270000,
    "produce_date": "2017-01-20"
}
1
2
3
4
5
6
7
/**
 * 按品牌名搜索
 */
@Test
public void searchByBrand() {
    SearchResponse response = client.prepareSearch("car_shop")
            .setTypes("cars")
            .setQuery(QueryBuilders.matchQuery("brand", "宝马"))
            .get();
    System.out.println(response);
}

/**
 * 多字段搜索
 */
@Test
public void multiMatchQuery() {
    SearchResponse response = client.prepareSearch("car_shop")
            .setTypes("cars")
            .setQuery(QueryBuilders.multiMatchQuery("宝马", "brand", "name"))
            .get();
    System.out.println(response);
}

/**
 * terms 搜索
 */
@Test
public void commonTermsQuery() {
    SearchResponse response = client.prepareSearch("car_shop")
            .setTypes("cars")
            .setQuery(QueryBuilders.commonTermsQuery("name", "宝马320"))
            .get();
    System.out.println(response);
}

/**
 * 前缀搜索
 */
@Test
public void prefixQuery() {
    SearchResponse response = client.prepareSearch("car_shop")
            .setTypes("cars")
            .setQuery(QueryBuilders.prefixQuery("name", "宝"))
            .get();
    System.out.println(response);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47