My linux world » Java Spring – ElasticSearch

Java Spring - ElasticSearch


Contents

Prerequistes

Please read : Java spring – quickstart

Configuration

ElasticSearchConfig.java

@Configuration
@EnableElasticsearchRepositories(basePackages = "net.rabahi.repository")
public class ElasticSearchConfig {
 
	@Value("${elasticsearch.home:/usr/local/elasticsearch}")
	private String elasticsearchHome;
 
	private static Logger logger = LoggerFactory.getLogger(ElasticSearchConfig.class);
 
	/**
	 * @return
	 */
	@Bean
	public Client client() {
		try {
			final Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data");
 
			// @formatter:off
 
			final Settings.Builder elasticsearchSettings =
					Settings.settingsBuilder().put("http.enabled", "false")
					.put("path.data", tmpDir.toAbsolutePath().toString())
					.put("path.home", elasticsearchHome);
			// @formatter:on
 
			logger.debug(tmpDir.toAbsolutePath().toString());
 
			return new NodeBuilder().local(true).settings(elasticsearchSettings.build()).node().client();
		} catch (final IOException ioex) {
			logger.error("Cannot create temp dir", ioex);
			throw new RuntimeException();
		}
	}
 
	/**
	 * @return
	 */
	@Bean(name="elasticsearchTemplate")
	public ElasticsearchOperations elasticsearchTemplate() {
		return new ElasticsearchTemplate(client());
	}
}

ArticleRepository

@Repository
public interface ArticleRepository extends ElasticsearchRepository<Article, String> {
 
    /**
     * @param name
     * @param pageable
     * @return
     */
    Page<Article> findByAuthorsName(String name, Pageable pageable);
 
    /**
     * @param name
     * @param pageable
     * @return
     */
    @Query("{\"bool\": {\"must\": [{\"match\": {\"authors.name\": \"?0\"}}]}}")
    Page<Article> findByAuthorsNameUsingCustomQuery(String name, Pageable pageable);
}

Model

The first model, is Author :

public class Author {
 
    private String name;
 
    public Author() {
    	// empty constructor.
    }
 
    public Author(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}

The second model, is Article. An Article can have many authors :

@Document(indexName = "blog", type = "article")
public class Article {
 
    @Id
    private String id;
 
    @MultiField(mainField = @Field(type = String), otherFields = { @InnerField(index = not_analyzed, suffix = "verbatim", type = String) })
    private String title;
 
    @Field(type = Nested)
    private List<Author> authors;
 
    @Field(type = String, index = not_analyzed)
    private String[] tags;
 
    public Article() {
    	// empty constructor.
    }
 
    public Article(String title) {
        this.title = title;
    }
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public List<Author> getAuthors() {
        return authors;
    }
 
    public void setAuthors(List<Author> authors) {
        this.authors = authors;
    }
 
    public String[] getTags() {
        return tags;
    }
 
    public void setTags(String... tags) {
        this.tags = tags;
    }    
}

Requests

Search author by name

// request :
final Page<Article> articleByAuthorName = articleService.findByAuthorName(authorName, new PageRequest(0, 10));
 
// the number of results :
articleByAuthorName.getContent().size();
 
// the result list :
articleByAuthorName.getContent();

Search article by title

// request :
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchQuery("title", articleTitle))
				.build();
List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
 
// the number of results :
articles.size();
 
// the result list :
articles;

Seach article when title match at least 90%

// request :
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchQuery("title", articleTitle)
				.minimumShouldMatch("90%"))
				.build();
		List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
 
// the number of results :
articles.size();
 
// the result list :
articles;

Copyright © 2023 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.

Fork me on GitHub