Abdalrhman Alkraien
Abdalrhman Alkraien

Reputation: 101

Elasticsearch with spring boot when using index query return nullPointerExciption

I am using Elasticsearch with spring boot. A post request returns a null pointer exception, because index query is null value doesn't have index name or any things.

Look at my code

Service :

public List<Product> createProducts() {
    List<Product>productList = new ArrayList<>();

    for (Integer i = 0; i < 200; i++)
    {
        Product product = new Product();
        product.setId(Long.parseLong(i.toString()));
        product.setProductName(generateName());
        product.setProductPrice(generatePrice());
        product.setCategory(generateCategory());

        if(!product.validation().equals(""))
        {
            throw new BadRequestAlertException(product.validation(),"Product","check input");
        }
        IndexQuery indexQuery=new IndexQueryBuilder().withId(i.toString()).build(); //return null
        elasticsearchOperations.index(indexQuery); // here is error becouse index is null
        productList.add(product);
    }

    return productList;
}

And this is the entity:

@JsonInclude(value = JsonInclude.Include.NON_NULL)
@Document(indexName = "product",type = "product")
public class Product implements Serializable {
    private static final long serialVersionUID = 6320548148250372657L;

    @Id
    private Long id;

    @Field(type = FieldType.Text)
    private String productName;

    @Field(type = FieldType.Text)
    private String category;

    @Field(type = FieldType.Double)
    private  Double productPrice;

This is the repostory:

public interface ProductSearchRepostory extends ElasticsearchRepository<Product,Long> {
    List<Product> findByProductName(String name);
    List<Product> findByCategory(String category);
}

Upvotes: 0

Views: 1004

Answers (1)

susheem_k
susheem_k

Reputation: 156

You need to let the elasticsearchOperations.index method know which index to save the data in.

As per the documentation present for Spring Data Elasticsearch, in the newer versions, the index method expects an IndexCoordinates object which tells the client which index to put the data in. For the older versions ( < 4.0), this is inferred by the client based on the entity object that is being indexed.

In your code, can you please try to pass the entity while building the IndexQuery. Something like, new IndexQueryBuilder().withId(i.toString()).withObject(product).build()

Upvotes: 0

Related Questions