ElasticSearch整合springboot实战

1、添加maven依赖
 
            org.springframework.boot
            spring-boot-starter-amqp
        
2、es配置
@Configuration
public class ElasticSearchConfig {

    @Bean
    public TransportClient client() throws UnknownHostException {
        // 设置端口名字
        InetSocketTransportAddress node = new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300);
        // 设置名字
        Settings settings = Settings.builder().put("cluster.name", "wgRoy").build();

        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(node);
        return client;
    }
3、es controller 测试
/**
 * Created by mc on 17/10/26.
 */
@RestController
public class ElasticSearchController {

    @Autowired
    private TransportClient client;

    @PostMapping("add/book/novel")
    @ResponseBody
    public ResponseEntity add(@RequestParam("title") String title, @RequestParam("author") String author, @RequestParam("content") String content) {
        try {

            IndexResponse response = client.prepareIndex("book", "novel", "1")
                    .setSource(jsonBuilder()
                            .startObject()
                            .field("author", author)
                            .field("title", title)
                            .field("content", content)
                            .endObject()
                    ).get();
            return new ResponseEntity(response, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("/get/book/novel")
    @ResponseBody
    public ResponseEntity get(@RequestParam(name = "id") String id) {
        GetRequestBuilder requestBuilder = client.prepareGet("book", "novel", "1");
        GetResponse response = requestBuilder.execute().actionGet();
        System.out.println(response.getSourceAsString());
        return new ResponseEntity(response.getSourceAsString(), HttpStatus.OK);
    }
4、测试结果




你可能感兴趣的:(数据库搜索引擎)