elasticsearch初探

Elasticsearch:一個集羣性質的Lucene搜索引擎java

由於項目須要實現按關鍵字匹配排序功能,原本想用Lucence的,可是L自己只是一個基礎library,實際應用的話目測代碼量比較大,小公司實現比較吃力,因此使用了elasticsearch,能夠集羣便於擴展。初次使用,介紹一下簡單的入門,不涉及任何高端技巧,熟悉的朋友不用看了,浪費時間。node

項目一直使用的spring-boot-starter,順便找了一下,果真找到有社區貢獻的集成jar,很厚臉皮的直接拿過來用了,項目地址:https://github.com/spring-projects/spring-data-elasticsearch,注意:這裏的client版本支持的是1.5.2,官方最新版本已經到2.1了,社區版本目前支持較低,反正我是初學,先學會使用。git

開始動手:github

  1. 添加依賴spring

<!-- maven -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-elasticsearch</artifactId>
    <version>1.3.0.RELEASE</version>
</dependency>
# gradle
dependencies {
    compile "org.springframework.boot:spring-boot-starter-data-elasticsearch"
}
  1. 配置apache

    <!-- xml -->
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
       xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <elasticsearch:node-client id="client" local="true"/>
    
    <bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="client"/>
    </bean>
    
    </beans>

    注意local="true",表示client啓動在本地,經試驗,沒有什麼實際用途,內存佔用嚴重,裏面在集成店別的東西,很容易內存溢出,僅做演示用。Transport Client配置(其實就是鏈接遠程服務):app

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
       xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <elasticsearch:repositories base-package="com.xyz.acme"/>
    
    <elasticsearch:transport-client id="client" cluster-nodes="ip:9300,ip:9300" cluster-name="elasticsearch" />
    
    <bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="client"/>
    </bean>
    </beans>
#java config:
#application.properties:

esearch.host=192.168.199.150
esearch.port=9300
@Configuration
@EnableElasticsearchRepositories(basePackages = "org/aybx/wishes/user/elastic")
public class ElasticSearchConfig {

    @Value("${esearch.port}") int port;
    @Value("${esearch.host}") String hostname;

    @Bean
    public ElasticsearchOperations elasticsearchTemplate() {
        return new ElasticsearchTemplate(client());
    }

    @Bean
    public Client client(){
        TransportClient client= new TransportClient();
        TransportAddress address = new InetSocketTransportAddress(hostname, port);
        client.addTransportAddress(address);
        return client;
    }
}

basePackages包含繼承spring-dataRepositorieselasticsearch

  1. 個人包結構以下:
    圖片描述maven

ESUser類須要註解@Document(indexName = "user"),指定id,ES的目錄結構大概是/index/type/documentIdESUserRepository須要繼承ElasticsearchCrudRepository,Service是正常的業務代碼,測試代碼:spring-boot

@RunWith(value = SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BootStartup.class)
@WebAppConfiguration
@ActiveProfiles("scratch")
public class ESUserServiceTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(ESUserServiceTest.class);

    @Autowired
    IESUserService iesUserService;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Test
    public void testSave() throws Exception {
        ESUser user = new ESUser();
        user.setId(1L);
        user.setContent("接機,包房,作飯");

        user = iesUserService.save(user);

        LOGGER.info("user, {}", JSON.toJSONString(user));

        ESUser user1 = new ESUser();
        user1.setId(2L);
        user1.setContent("接機,包房");

        user1 = iesUserService.save(user1);

        LOGGER.info("user1, {}", JSON.toJSONString(user1));

        ESUser user2 = new ESUser();
        user2.setId(3L);
        user2.setContent("包房,作飯");

        user2 = iesUserService.save(user2);

        LOGGER.info("user2, {}", JSON.toJSONString(user2));
    }

    @Test
    public void testFind() throws Exception {
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(queryStringQuery("接機 OR 作飯")).withFields("content").build();
        List<ESUser> esUsers = elasticsearchTemplate.queryForList(searchQuery, ESUser.class);
        for (ESUser user : esUsers) {
            LOGGER.info("user:{}, content:{}", user.getId(), user.getContent());
        }
    }
}

這裏沒有用service調用,寫了一個簡單的查詢,接機作飯中間的OR表示匹配或的意思,還有不少能夠操做的地方,詳細能夠參考官方文檔,好比增長一個條件的權重,篩選多餘的filed,篩選子類的屬性等等;感受複雜到不行,不過也對,搜索的時候必然會有這樣的須要,也很符合實際狀況。

最後說一下ES的插件用法,好比常見的monitor功能:Marvel,安裝,/bin/plugin install elasticsearch/marvel/latest,這是低版本的裝法,新版參考文檔

相關文章
相關標籤/搜索