elasticsearch 5.4 search

 

 

@Test
    public void testESCreateIndex() throws IOException, InterruptedException {

        String esRoot = "http://localhost:9200/stations";//index地址

        String result = restTemplate.getForObject(esRoot, String.class, "");
        System.out.println(result);
        restTemplate.delete(esRoot);
        HttpEntity<String> formEntity = new HttpEntity<String>(IOUtil.loadData2String(AppTest.class.getResource("/mapper.json").getPath()), new HttpHeaders());
        restTemplate.put (esRoot, formEntity);

    }

 

mapping.json

 

 

{
  "mappings": {
    "station": {
      "properties": {
        "company": {
          "type": "text",
          "analyzer": "lc_index",
          "search_analyzer": "lc_search",
          "term_vector": "with_positions_offsets"
        },
        "address": {
          "type": "text",
          "analyzer": "lc_index",
          "search_analyzer": "lc_search",
          "term_vector": "with_positions_offsets"
        },
        "areaName": {
          "type": "text",
          "analyzer": "lc_index",
          "search_analyzer": "lc_search",
          "term_vector": "with_positions_offsets"
        },
        "loc": {
          "type": "geo_point"
        }
      }
    }
  }
}

 

@Test
    public void testESSearch() throws UnknownHostException {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
        String[] searchFieldNames = {"company", "address"};
        QueryBuilder qb = boolQuery().must(multiMatchQuery("Jiangsu Drum Tower", searchFieldNames).type(PHRASE).analyzer("lc_index"));


        SearchRequestBuilder req = client.prepareSearch(INDEX)
                .setTypes(TYPE).setExplain(true)
                .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.DESC)
                .setQuery(qb)
                .setFetchSource(searchFieldNames,null)
                .setFrom(0).setSize(100);

        /**
         * View search json string
         */
        System.out.println(req.toString());

        
        SearchResponse response = req.get();
        if (response.getHits().getHits().length > 0) {
            for (SearchHit hit : response.getHits().getHits()) {
                for (int i = 0; i < searchFieldNames.length; i++) {
                    System.out.print("|  "+hit.getSourceAsMap().get(searchFieldNames[i]) );
                }
                System.out.println();
            }
        }


// on shutdown

        client.close();
    }

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326446091&siteId=291194637
5.4