react-native - 未强制执行 ReactiveSearch 默认查询

标签 react-native elasticsearch

尝试在响应式(Reactive)搜索组件中应用默认查询,但没有效果

import React from 'react';
import {
    NavigationScreenProps,
    NavigationScreenConfig, NavigationActions,
} from 'react-navigation';
import {
    ChatHeader,
    ChatHeaderNavigationStateParams,
} from '@src/components/messaging';
import {
    Conversation,
} from '@src/core/model';
import {conversation5} from '@src/core/data/conversation';
import {StyleSheet, Text, Image, TouchableWithoutFeedback} from 'react-native';
import {
    ReactiveBase,
    DataSearch,
    ReactiveList,
} from '@appbaseio/reactivesearch-native';

import {ScrollView, View} from 'react-native';
import {Icon, ListItem} from '@kitten/ui';
import LottieView from 'lottie-react-native';

import {SearchHeader} from '@src/components/search/search.header';
import {userProvider} from '../../../../domain/auth/UserProvider';
import {Screen} from '../../../../core/navigation/screens';
import Tts from 'react-native-tts';
import {StarIconOutline} from '@src/assets/icons';
import axios, {AxiosError, AxiosResponse} from 'axios';
import {Config} from '../../../../constants/Config';
import {User} from '@domain/models';
import DoubleClick from 'react-native-double-tap';
import {Notification} from 'react-native-in-app-message';
import AnimatedLoader from 'react-native-animated-loader';

interface State {
    newMessageText: string;
    conversation: Conversation;
    isLoading: boolean;
    message: string;
}


const styles = StyleSheet.create({
    container: {
        padding: 10,
        marginTop: 25,
    },
    image: {
        width: 100,
        height: 100,
    },
    result: {
        flexDirection: 'row',
        width: '100%',
        margin: 5,
        alignItems: 'center',
    },
    notification: {
        flexDirection: 'row',
        width: '100%',
        margin: 5,
        padding: 5,
        alignItems: 'flex-start',
    },
    item: {
        flexDirection: 'column',
        paddingLeft: 10,
    },
    title: {
        fontWeight: 'bold',
    },
    lottie: {
        width: 100,
        height: 100,
    },
    iconx: {
        width: 50,
        height: 40,
        marginLeft: -3,
        marginBottom: -10,
        padding: 5,
    },
    notificationText: {
        marginTop: 11,
    },
});


export class SearchContainer extends React.Component<NavigationScreenProps, State> {
    private notification: Notification;
    private token: string;

    public state: State = {
        newMessageText: '',
        conversation: conversation5,
        isLoading: false,
        message: '',
    };

    private infiniteAnimationIconRef: React.RefObject<Icon> = React.createRef();

    static navigationOptions: NavigationScreenConfig<any> = ({navigation, screenProps}) => {
        const headerProps: ChatHeaderNavigationStateParams = {
            interlocutor: navigation.getParam('interlocutor', conversation5.interlocutor),
            lastSeen: navigation.getParam('lastSeen', 'today'),
            onBack: navigation.getParam('onBack'),
            onProfile: navigation.getParam('onProfile'),
        };

        const header = (navigationProps: NavigationScreenProps) => {
            return (
                <SearchHeader
                    {...navigationProps}
                    {...headerProps}
                />
            );
        };

        return {...navigation, ...screenProps, header};
    };

    public async componentWillMount(): void {
        this.props.navigation.setParams({
            onBack: this.onBackPress,
        });

        await userProvider.get().then((data) => {
            this.token = data.token;
        }).catch(() => {
            this.props.navigation.navigate(Screen.Login);
        });
    }

    public componentDidMount() {
        this.setState({
            isLoading: false,
        });

    }

    private onBackPress = (): void => {
        this.props.navigation.goBack(null);
    };

    private say(deText): void {
        Tts.setDefaultLanguage('de-DE');
        Tts.setDucking(true);
        Tts.speak(deText);
    }

    private star(id): void {
        this.setState({isLoading: true});

        axios.post(Config.service.stars.url, {
            sentence_id: id,
        }, {
            headers: {
                'Authorization': `Bearer ${this.token}`,
            },
        }).then((response: AxiosResponse<UserData>) => {
            this.setState({message: 'Star added!'});
            setTimeout(() => this.notification.show(), 100);
            this.setState({isLoading: false});
        }).catch((error: AxiosError) => {
            let errorMessage = null;
            try {
                const code = error.response.request.status;
                if (code === 401) {
                    this.props.navigation.navigate(Screen.Login);
                } else if (code === 422) {
                    errorMessage = 'Star was added already for this sentence!';
                } else {
                    errorMessage = 'Service is unavailable, please try again in a few!';
                }
            } catch (e) {
                errorMessage = 'Service is unavailable, please try again in a few!';
            }


            this.setState({...this.state, message: errorMessage});
            setTimeout(() => this.notification.show(), 100);
            this.setState({isLoading: false});
        });
    }

    public render(): React.ReactNode {
        return (

            <ReactiveBase
                app='myapp'
                url='http://xxx.xxxxxx.io'
                headers={{'X-Api-Key': 'xxxxxxxxxxxxxxxxxxxxxxxxx'}}>
                <View>
                    <DataSearch
                        componentId='searchbox'
                        dataField={[
                            'sentence',
                            'sentence.en',
                            'sentence.de',
                            'raw.translated',
                        ]}
                        value='1'
                        highlight={true}
                        placeholder='words or expressions'
                        defaultQuery={() => ({
                            query: {
                                match: {
                                    message: {
                                        query: 'test',
                                    },
                                },
                            },
                        })}
                        autosuggest={false}
                    />
                </View>
                <Notification
                              customComponent={(
                                  <View style={styles.notification}>
                                      <LottieView
                                          style={styles.iconx}
                                        source={require('@src/animations/warning.json')}
                                        colorFilters={[{
                                          keypath: 'button',
                                          color: '#F00000',
                                        }, {
                                          keypath: 'Sending Loader',
                                          color: '#F00000',
                                        }]}
                                        autoPlay
                                        loop={true}
                                      />
                                        <Text style={styles.notificationText}>{this.state.message}</Text>
                                  </View>
                              )}
                              ref={(c) => this.notification = c}
                />
                <AnimatedLoader
                    visible={this.state.isLoading}
                    overlayColor='rgba(255,255,255,0.75)'
                    source={require('@src/animations/loader.json')}
                    animationStyle={styles.lottie}
                    speed={1}
                />
                <ScrollView
                    stickyHeaderIndices={[1]}
                    nativeID={'scoller'}
                >
                    <View>

                        <ReactiveList
                            componentId='results'
                            dataField='sentence.de'
                            size={7}
                            showResultStats={false}
                            pagination={true}
                            infiniteScroll={true}
                            scrollTarget={'scroller'}
                            react={{
                                and: 'searchbox',
                            }}
                            defaultValue={'Harry Potter'}
                            onData={(res, idx) => (

                                <View style={styles.result} key={res._id}>
                                    <DoubleClick
                                        singleTap={() => {
                                            this.star(res._id);
                                        }}
                                        doubleTap={() => {
                                        }}
                                        delay={1000}
                                    >
                                        <Icon name='star-outline' fill='#FF9999' width='30' height='50'/>

                                    </DoubleClick>
                                    <ListItem
                                        onPress={() => this.say(res.sentence.de)}
                                        title={res.sentence.de}
                                        description={res.raw.translated}
                                    />

                                </View>


                            )}
                        />
                    </View>
                </ScrollView>
            </ReactiveBase>
        );
    }
}

<DataSearch
                        componentId='searchbox'
                        dataField={[
                            'sentence',
                            'sentence.en',
                            'sentence.de',
                            'raw.translated',
                        ]}
                        value='1'
                        highlight={true}
                        placeholder='words or expressions'
                        defaultQuery={() => ({
                            query: {
                                match: {
                                    message: {
                                        query: 'test',
                                    },
                                },
                            },
                        })}
                        autosuggest={false}
                    />

最佳答案

试试这个(即使用 filter 而不是 should ):

                <ReactiveComponent
                    componentId='filterbox'
                    customQuery={props => ({
                        query: {
                            'bool': {                          
                                'filter': [{
                                    'ids': {
                                        'type': 'mydoctype',
                                        'values': ['TK6IRm4BK9UoLvJay0OC', 'Ra6IRm4BK9UoLvJaykMD'],
                                    },
                                }]
                            },
                        }
                    })}
                />

关于react-native - 未强制执行 ReactiveSearch 默认查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58753460/

相关文章:

elasticsearch - 如果字符串在数组中包含90%的单词,则返回

javascript - 使用 React Native 异步返回一个值

reactjs - 我们是否需要对 React 应用程序进行跨浏览器测试

react-native - 如何更改Xcode react-native run-ios指向的版本?

elasticsearch - 基于logstash中已转换的unix时间戳记的值的索引

elasticsearch - Elasticsearch 地理空间搜索实现

elasticsearch - 如何为模型添加术语以从文本中提取实体

elasticsearch - Elasticsearch 查询词和评分

ios - 打印 : Entry, ":CFBundleIdentifier",在 React Native IOS 版本中不存在

react-native - 防止系统键盘在 React Native 中按下 TextInput 时显示