Showing posts with label hello world. Show all posts
Showing posts with label hello world. Show all posts

Wednesday, 16 June 2021

Lucene: Hello World Application

In this post, I am going to explain how to add documents to Lucene index and query on specific fields of the document.

 

Document 1

"id": "1"
"title" : "Lucene in Action"
"description" : "Lucene is a platform where we can index our data to make it searchable."

 

Document 2

"id" : "2"
"title" : "Java in Action"
"description" : "Java is a platform and programming language to build Enterprise Applications"

 

Follow below step by step procedure to add above documents to Lucene index and query.

 

Procedure to add documents to Lucene index

Step 1: Define Index writer configuration.

Analyzer analyzer = new StandardAnalyzer();
IndexWriterConfig config = new IndexWriterConfig(analyzer);

 

Step 2: Define a Directory to store the documents.

Directory directory = new MMapDirectory(new File("/Users/Shared/lucene").toPath(), NoLockFactory.INSTANCE);

 

Step 3: Define Document instances to represent the documents to add to Lucene index.

Document doc1 = new Document();
doc1.add(new TextField("id", "1", Field.Store.YES));
doc1.add(new TextField("title", "Lucene in Action", Field.Store.YES));
doc1.add(new TextField("description", "Lucene is a platform where we can index our data to make it searchable.", Field.Store.YES));

Document doc2 = new Document();
doc2.add(new TextField("id", "2", Field.Store.YES));
doc2.add(new TextField("title", "Java in Action", Field.Store.YES));
doc2.add(new TextField("description", "Java is a platform and programming language to build Enterprise Applications", Field.Store.YES));

 

Step 4: Define IndexWriter and add documents to the index.

try (IndexWriter indexWriter = new IndexWriter(directory, config)) {
	indexWriter.addDocument(doc1);
	indexWriter.addDocument(doc2);
}

Procedure to query Lucene Index.

Step 1: Open directory using IndexReader.

IndexReader indexReader = DirectoryReader.open(directory)


Step 2: Define IndexSearcher using IndexReader.

IndexSearcher indexSearcher = new IndexSearcher(indexReader);


Step 3: Define Query instance to query on specific field.

QueryBuilder queryBuilder = new QueryBuilder(analyzer);
Query query = queryBuilder.createPhraseQuery("title", "Lucene", 0);


Step 4: Use search method of IndexSearcher to query Lucene index.

TopDocs docs = indexSearcher.search(query, maxHitsPerPage);
ScoreDoc[] hits = docs.scoreDocs;
System.out.print("Total Hits: " + docs.totalHits);
System.out.print("Results: ");
for (int i = 0; i < hits.length; i++) {
	Document d = indexSearcher.doc(hits[i].doc);
	System.out.println("Content: " + d.get("title"));
}



Find the below working application.

 

App.java

package com.sample.app;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.MMapDirectory;
import org.apache.lucene.store.NoLockFactory;
import org.apache.lucene.util.QueryBuilder;

public class App {

	public static void main(String args[]) throws IOException {

		Analyzer analyzer = new StandardAnalyzer();
		IndexWriterConfig config = new IndexWriterConfig(analyzer);

		Directory directory = new MMapDirectory(new File("/Users/Shared/lucene").toPath(), NoLockFactory.INSTANCE);

		Document doc1 = new Document();
		doc1.add(new TextField("id", "1", Field.Store.YES));
		doc1.add(new TextField("title", "Lucene in Action", Field.Store.YES));
		doc1.add(new TextField("description", "Lucene is a platform where we can index our data to make it searchable.",
				Field.Store.YES));

		Document doc2 = new Document();
		doc2.add(new TextField("id", "2", Field.Store.YES));
		doc2.add(new TextField("title", "Java in Action", Field.Store.YES));
		doc2.add(new TextField("description",
				"Java is a platform and programming language to build Enterprise Applications", Field.Store.YES));

		try (IndexWriter indexWriter = new IndexWriter(directory, config)) {
			indexWriter.addDocument(doc1);
			indexWriter.addDocument(doc2);
		}

		QueryBuilder queryBuilder = new QueryBuilder(analyzer);
		Query query = queryBuilder.createPhraseQuery("title", "Lucene", 0);
		int maxHitsPerPage = 10;
		
		try (IndexReader indexReader = DirectoryReader.open(directory)) {
			IndexSearcher indexSearcher = new IndexSearcher(indexReader);

			TopDocs docs = indexSearcher.search(query, maxHitsPerPage);
			ScoreDoc[] hits = docs.scoreDocs;
			System.out.println("Total Hits: " + docs.totalHits);
			System.out.println("Results: ");
			for (int i = 0; i < hits.length; i++) {
				Document d = indexSearcher.doc(hits[i].doc);
				System.out.println("Content: " + d.get("title"));
			}
		}

	}

}


Output

Total Hits: 1 hits
Results: 
Content: Lucene in Action








 

 

 

 

 

 

Previous                                                    Next                                                    Home

Tuesday, 15 June 2021

Junit 5: Hello World Application using maven

Step 1: Open Eclipse, and create new maven project junit5-examples.

 

File -> New -> Other.

Under maven -> Maven Project.

 


 

Click on Next button.

 


 

Select the checkbox ‘Create s simple project (skip archetype selection)’, click on Next button.




Give Group Id as ‘com.sample.app’ and Artifact Id as junit5-examples and Version as 1 and click on Finish button.

 

Total project structure looks like below.




Step 2: Update pom.xml with maven dependencies.

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>junit5-examples</artifactId>
	<version>1</version>

	<properties>
		<junit-jupiter.version>5.6.1</junit-jupiter.version>
		<maven-surefire-plugin.version>3.0.0-M5</maven-surefire-plugin.version>

		<java.version>1.8</java.version>
		<maven.compiler.target>${java.version}</maven.compiler.target>
		<maven.compiler.source>${java.version}</maven.compiler.source>

		<project.encondig>UTF-8</project.encondig>
		<project.build.sourceEncoding>${project.encondig}</project.build.sourceEncoding>
		<project.reporting.outputEncoding>${project.encondig}</project.reporting.outputEncoding>
	</properties>


	<dependencies>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-engine</artifactId>
			<version>${junit-jupiter.version}</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>${maven-surefire-plugin.version}</version>
			</plugin>
		</plugins>
	</build>
</project>

 

Step 3: Create a package com.sample.app under src/test/java folder.

 

Step 4: Define AppTest class in com.sample.app package.

 

AppTest.java

 

package com.sample.app;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

public class AppTest {

	@Test
	public void helloTest() {
		assertTrue(true);
	}

}

 

Step 5: Run the testcases.

 

Right click on AppTest.java class -> Run As -> Junit Test.

 

 


You will see the test results under Junit window.


 


 

 

You can download complete working application from this link.

https://github.com/harikrishna553/junit5/tree/master/junit5-examples

Previous                                                    Next                                                    Home

Tuesday, 20 April 2021

Guava Cache: Hello world application

In this post, I am going to explain,

a.   How to create a cache using Guava CacheBuilder

b.   How to store the object into the cache

c.    How to retrieve the objects from cache

 

How to create a cache?

You can create a cache using CacheBuilder class.

 

Example

Cache<Integer, Employee> empCache = CacheBuilder.newBuilder().maximumSize(500).expireAfterAccess(15, TimeUnit.SECONDS).expireAfterWrite(30, TimeUnit.SECONDS).build();

 

How to add an object to the cache?

Using put method, you can add a <key,value> pair into the cache.

 

Example

empCache.put(1, new Employee(1, "Krishna", "Gurram"));

 

How to retrieve an element from the cache?

Using ‘getIfPresent’ method, you can retrieve an element from the cache.

 

Example

Employee emp1 = empCache.getIfPresent(1);

If there is an entry exist in the cache for the key 1, this method return the object, else null.

 

Find the below working application.

 

Employee.java 

package com.sample.app.cache.model;

public class Employee {
	private Integer id;
	private String firstName;
	private String lastName;

	public Employee(Integer id, String firstName, String lastName) {
		super();
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
	}

}

 

HelloWorld.java

package com.sample.app.cache;

import java.util.concurrent.TimeUnit;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.sample.app.cache.model.Employee;

public class HelloWorld {
	private static void printEmployee(Employee emp, Integer id) {
		if (emp == null) {
			System.out.println("Employee not exist for the id " + id);
			return;
		}
		System.out.println(emp);
	}

	public static void main(String args[]) throws InterruptedException {
		Cache<Integer, Employee> empCache = CacheBuilder.newBuilder().maximumSize(500)
				.expireAfterAccess(15, TimeUnit.SECONDS).expireAfterWrite(30, TimeUnit.SECONDS).build();

		empCache.put(1, new Employee(1, "Krishna", "Gurram"));
		empCache.put(2, new Employee(2, "Sailu", "PTR"));

		System.out.println("Getting employee with ids 1, 2 and 3 from empCache");
		Employee emp1 = empCache.getIfPresent(1);
		Employee emp2 = empCache.getIfPresent(2);
		Employee emp3 = empCache.getIfPresent(3);

		printEmployee(emp1, 1);
		printEmployee(emp2, 2);
		printEmployee(emp3, 3);

		System.out.println("\nGoing to sleep for 35 seconds\n");
		TimeUnit.SECONDS.sleep(35);

		emp1 = empCache.getIfPresent(1);
		emp2 = empCache.getIfPresent(2);
		emp3 = empCache.getIfPresent(3);

		System.out.println("Getting employee with ids 1, 2 and 3 from empCache");
		printEmployee(emp1, 1);
		printEmployee(emp2, 2);
		printEmployee(emp3, 3);

	}

}

 

Output

Getting employee with ids 1, 2 and 3 from empCache
Employee [id=1, firstName=Krishna, lastName=Gurram]
Employee [id=2, firstName=Sailu, lastName=PTR]
Employee not exist for the id 3

Going to sleep for 35 seconds

Getting employee with ids 1, 2 and 3 from empCache
Employee not exist for the id 1
Employee not exist for the id 2
Employee not exist for the id 3

 



Previous                                                    Next                                                    Home