Not able to configure haystack-elasticsearch for search in android

74 Views Asked by At

I started with this [tutorial][1], but I was not able to understand how to set it up for search in android app. So far, I've made a model using django REST framework, then used retrofit in android to make GET, PUT and POST requests.

Now I want to search my products by name.

The above tutorial was trying to make search HTML page and type the query in that HTML page, but I want an endpoint where I can send GET requests for searching.

Please help me to understand how to do it.

class Product(models.Model):
        name=models.CharField(max_length=50)
        mrp = models.DecimalField(max_digits=20)
        company=models.CharField(max_length=100)

class ProductSerializer(serializers.ModelSerializer):

    class Meta:
        model = Product
        fields = ('id', 'name', 'mrp', 'company')

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer  

    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class ProductIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    name = indexes.CharField(model_attr='name')
    company=indexes.CharField(model_attr='company')

    def get_model(self):
        return Product

    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.all()

Now how should I use this ItemIndex to make search url using haystack. [1]: http://django-haystack.readthedocs.io/en/v2.6.0/tutorial.html

1

There are 1 best solutions below

4
Ykh On

in DRF:

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    permission_classes = (IsAuthenticated,)

    @list_route(methods=['POST'])
    def search(self, request):
        key = request.data['key']
        queryset = Product.objects.filter(name__icontains=key)
        serializer = ProductSerializer(queryset, many=True)
        return Response(serializer.data)

in Android Okhttp3 demo:

    RequestBody requestBody = new FormBody.Builder()
            .add("key", ProductName)
            .build();
    Request request = new Request.Builder()
            .post(requestBody)
            .url(Constants.ProductSearch)
            .build();

    HttpClientUtil.getClient().newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {}

        @Override
        public void onResponse(Call call, final Response response) throws IOException {
            final String data = response.body().string();
            Log.e("Http",data);
        }
    });